my code prints "Narcissistic Numbers" up to 600,000.
http://mathworld.wolfram.com/NarcissisticNumber.html
on the website is says this number is "An -digit number that is the sum of the th powers of its digits is called an -narcissistic number."
( such as 153 = (1*1*1) + (5*5*5) + (3*3*3) )
the problem is my code runs slowly if i try to calculate numbers higher than 1 million, if possible i'd like to go up as far as maybe 2 or 3 million.
do you know if there is anything i can change to speed up this code?
class NarcissisticNumbers {
public static void main(String[] args) {
for(int i = 1; i < 600000; i++) {
if(isNarcissistic(i)) System.out.print(i+" ");
}
}
static boolean isNarcissistic(int x) {
String num = String.valueOf(x);
for(int i = 1; i <= 7; i++) {
int sum = 0;
for(int j = 0; j < num.length(); j++) {
sum += Math.pow(Integer.parseInt(num.substring(j,j+1)),i);
if(sum > x) return false;
}
if(sum == x) return true;
}
return false;
}
}