prakashjp.me
prakashjp.me

Reputation: 1

Armstrong number logic error

Here I've code to print armstrong numbers until some particular range. But this programs doesnt prints all the numbers within the range. It just prints armstrong number within range of 1000. Whats wrong in this code?

public static void main(String[] args) {
    long N, temp, sum = 0;
    Scanner ip = new Scanner(System.in);
    System.out.print("Enter the range: ");
    N = ip.nextLong();
    for (long i = 1; i < N; i++) {
        temp = i;
        while (temp > 0) {
            long rem = temp % 10;
            sum = sum + (rem * rem * rem);
            temp = temp / 10;
        }
        if (sum == i) {
            System.out.println(" " + i);
        }
        sum = 0;
    }
    ip.close();
}

when the input is 100000 it just prints

Enter the range: 100000
 1
 153
 370
 371
 407

Upvotes: 0

Views: 63

Answers (1)

Debanik Dawn
Debanik Dawn

Reputation: 799

According to the definition of Armstrong numbers, each digit in the number is to be raised to n where is the number of digits in the number.

However your logic does not implement that. It only raises digits to the third power.

That's why your code fails.

Here you go, use this code:

for (long i = 1; i < N; i++) {
    temp = i;
    int n=Long.toString(i).length();
    while (temp > 0) {
        long rem = temp % 10;
        sum = sum + (long) Math.pow(rem, n);
        temp = temp / 10;
    }
    if (sum == i) {
        System.out.println(" " + i);
    }
    sum = 0;
}

Ideone link here.

Upvotes: 2

Related Questions