# Javascript Armstrong Number Test Case Errors

## 21 February 2019 - 1 answer

The question I'm solving is:

Write a javascript program which returns true when a given number is Armstrong number and false otherwise. Any n digit number is armstrong number if sum of nth power of each digit equals to the number itself. Example: `153` is a `3` digit armstrong number because sum of 3rd power of each digit equals to `153` (`153 = 1*1*1 + 5*5*5 + 3*3*3`).

Hint: Use `Math.pow(i,n)` to calculate nth power of `i`. Use `parseInt(i)` to get integer value of `i`. Your output code should be in the format `console.log("Result is ", variableName)`

My code is:

``````var num = prompt("Enter a number to check Armstrong");
var t = "Armstrong";
var f = "Not Armstrong";

function armst(x) {
var a = x, b, sum = 0;
while (a > 0) {
b = a % 10;
sum += (b * b * b);
a = parseInt(a / 10);
}

if (sum === x) {
return t;
} else {
return f;
}
}

var output = armst(num);
console.log("Result is : ", output);
``````

When I run this code on the course website it gives correct outputs but doesn't pass all the test cases according to the compiler.

Am I missing something? What could be improved?

For getting an narcissistic number/Armstrong number, you need to take the length of the number as string as `n` for taking the power for summing the value.

Just a personal word, because of the specification, I would take `Math.floor`, because you have already a number, instead of `parseInt`.

``````function armst(x) {
var value = parseInt(x, 10),
rest = value,
digit,
sum = 0,
n = x.toString().length;       // add toString, if a number is entered

while (rest) {
digit = rest % 10;
rest = Math.floor(rest / 10);
sum += Math.pow(digit, n);    // use it here
}

return sum === value
? "Armstrong"
: "Not Armstrong";
}

var num = prompt("Enter a number to check Armstrong"), // try with 54748
output = armst(num);

console.log("Result is: ", output);``````