Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript armstrong number test case errors

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?

like image 951
Aditya Singh Avatar asked Jan 28 '26 09:01

Aditya Singh


1 Answers

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);
like image 167
Nina Scholz Avatar answered Jan 31 '26 00:01

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!