-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathdoes-my-number-look-big-in-this.js
More file actions
29 lines (26 loc) · 976 Bytes
/
does-my-number-look-big-in-this.js
File metadata and controls
29 lines (26 loc) · 976 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function narcissistic( value ) {
const length = Math.floor(Math.log10(Math.abs(value))) + 1;
// a place to store the sum
let sum = 0;
let digits = value;
// while current value is greater than 0
while (digits > 0) {
// grab the last digit of the number
const digit = digits % 10;
// raise that digit to the length power, add the value to the sum
sum += Math.pow(digit, length);
// remove that digit from the value
digits = Math.floor(digits / 10);
}
return sum == value;
}
function narcissistic( value ) {
return [...value.toString()].reduce((sum, digit, i, {length}) => {
return sum + Math.pow(digit, length);
}, 0) == value;
}
console.log( narcissistic( 7 ), '7 is narcissistic' );
console.log( narcissistic( 23 ), '23 is not narcissistic' );
console.log( narcissistic( 153 ), '153 is narcissistic' );
console.log( narcissistic( 1634 ), '1634 is narcissistic' );
console.log( narcissistic( 371 ), '371 is narcissistic' );