Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

narcissistic numbers

807601Dec 29 2007 — edited Dec 29 2007
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;
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 26 2008
Added on Dec 29 2007
18 comments
387 views