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!

kaprekar numbers

807601Dec 18 2007 — edited Dec 18 2007
i have a problem with this code which prints "kaprekar numbers".
297 for example is a kaprekar number because 297*297 = 88209. (88+209 = 297)
9 is too, 9*9 = 81. 8+1 = 9.
http://en.wikipedia.org/wiki/Kaprekar_number

the problem is i can't think of any other way of doing it without those if statements in isKaprekar().
i'm only getting the right numbers below 3000 and i need 3 ifs for that. if i wanted to calculate kaprekars much higher than 3000 i would need a lot more if statements.

could anyone give me a few ideas on how i could do this without them?
here's my code:
class KaprekarNumbers {

    public static void main(String[] args) {
	for(int i = 1; i <=3000; i++) {
   	    if(isKaprekar(i)) System.out.print(i+" ");
   	}
    }

    static boolean isKaprekar(int n) {
	int nSquared = n*n, d = 10;
 	if(nSquared >999 && nSquared <10000) d = 100;
   	if(nSquared >9999 && nSquared <1000000) d = 1000;
	if(nSquared >999999 && nSquared <10000000) d = 10000;
   	int num1 = nSquared/d;
   	int num2 = nSquared%d;
	return (num1+num2) == n && num2>0;  //num2 >0 because of 10.
    }
}

 
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 15 2008
Added on Dec 18 2007
19 comments
552 views