public class ArmstsrongNumberExample {
public static long sum = 0;
static boolean isArmstrong(long n) {
long temp, digits=0, last=0;
temp = n;
while(temp>0) {
temp = temp/10;
digits++;
}
temp = n;
long powresult;
while(temp>0) {
last = temp % 10;
powresult = (long) Math.pow(last, digits);
sum = sum + powresult;
System.out.println(last +", "+ powresult +", "+ sum);
temp = temp/10;
}
System.out.println();
if(n==sum)
return true;
else return false;
}
public static void main(String args[]) {
long[] arms = new long[] {40028394225L, 42678290603L,
44708635679L, 49388550606L, 82693916578L,
94204591914L, 28116440335967L, 4338281769391370L,
4338281769391371L,
21897142587612075L,
35641594208964132L,
35875699062250035L,
1517841543307505039L,
3289582984443187032L,
4498128791164624869L,
4929273885928088826L};
System.out.println(arms[10] + " = armstrong number? " + isArmstrong(arms[10]));
System.out.println(sum + " = the sum");
}
}
This prg above will tell you if the number you are passing is an Armstrong number or not.
The encoded array contains armstrong numbers (I searched the net for a list of them.)
Problem-1:
It gives false for numbers starting from index 9 of the array! So:
Output:
3564159420896413
2 = armstrong number? false
3564159420896413
4 = the sum
Problem-2:
The above result was obtained with the run set to JDK-8.
If I change it to anything else, e.g. JDK-10 or 11, or JDK-17, I get this result:
Output:
3564159420896413
2 = armstrong number? false
3564159420896413
0 = the sum
I'm shocked by the result, why JVM can't calculate correctly?!... 8-)
I rewrote the program to count with BigInteger instead of longs.
Then it finally worked fine, there was no mismatch.
In the meantime I realized that probably the following line:
powresult = (long) Math.pow(last, digits);
perhaps this line might have caused the problem, because Math.pow() returns double, which can be unpunctual because of the double type, especially if I typecast it.
However, if I need to calculate exponentiation, and I need to work with large integers in the long range, and I want to get EXACT RESULTS... should I never use the Math.pow() method? Rather, should I always modify the code to use the BigInteger class?