Saturday, June 2, 2007

Q3: Armstrong Number(Narcissistic number)

Q: Print out all Narcissistic numbers between 100 and 999.

In number theory, a narcissistic number or pluperfect digital invariant (PPDI) or Armstrong number is a number that in a given base is the sum of its own digits to the power of the number of digits.

For example, the decimal (Base 10) number 153 is an Armstrong number, because:

1³ + 5³ + 3³ = 153
A:
public class Armstrong {
private static boolean isArmstrong(int n){
int base = n;
int size = Integer.toString(n).length();
int sum = 0, d=0;

for(int i=0; i < size; i++){
d = base %10;
base /=10;
sum += Math.pow(d, size);
}
if(sum == n) return true;
else return false;
}

public static int getArmstrongQuantity(int root, int floor){
int cnt =0;
for(int i=root; i < floor; i++){
if(isArmstrong(i)){
System.out.print(i + ", ");
cnt++;
}
}
System.out.println();
return cnt;
}

public static void main(String[] args) {
System.out.println("There are " +
Armstrong.getArmstrongQuantity(100, 999) +
" armstrong numbers between 100 and 999.");
}
}

result:
153, 370, 371, 407,
There are 4 armstrong numbers between 100 and 999.

No comments: