Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Narcissistic Number
// 1/11/2016
// A Narcissistic Number is a number which is the sum of its own digits, each
// raised to the power of the number of digits.
// For example, take 153 (3 digits):
// 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
// and 1634 (4 digits):
// 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
// The Challenge:
// Your code must return true or false depending upon whether the given number
// is a Narcissistic number.
// Error checking for text strings or other invalid inputs is not required,
// only valid integers will be passed.
// describe( "Narcissistic Function", function() {
// it( "should find small numbers are all narcissistic", function() {
// Test.expect( narcissistic( 7 ), "7 is narcissistic" );
// });
// it( "should find these numbers are narcissistic", function() {
// Test.expect( narcissistic( 371 ), "371 is narcissistic" );
// });
// });
// My Solution:
function narcissistic( value ) {
var arr1=value.toString().split("")
// console.log(arr1)
var sum=0;
for(var i=0;i<arr1.length;i++){
sum+=Math.pow(arr1[i],arr1.length)
console.log(sum)
}
if (sum===value) return true;
else return false;
}
narcissistic(153)
// I sometimes check other coders' solutions to see if I can learn something new.
// Below is other person's solution on this problem
function narcissistic( value ) {
var str = value + '';
var sum = 0;
for (var i = 0, len = str.length; i < len; i++){
sum += Math.pow(+str.substr(i, 1), len);
}
return (sum === value);
}
narcissistic(153)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.