Monday, May 24, 2010

Help with c program?

can u please tell me how to write a c program to generate adam numbers from 10 to 100.


an adam number is one which satisfies the following: the reverse of the square of a number is the square of the reverse of the number. that is if the number is 12 then 12^2=144,the reverse 441 which is 21^2

Help with c program?
#include%26lt;stdio.h%26gt;


void main()


{


int num, rev, sq, rev_sq;


int rev_int(int);//Function to get reverse of any number passed as parameter





for (num=10;num%26lt;100;num++)


{


sq = num*num; // square of all numbers from 10 to 100;


rev = rev_int(num); // gets reverse of num


rev_sq = rev_int(sq);// gets reverse of square





/* we check if the reverse of the square of the number is equal to the square of the reverse of the number.If found true then print the number else go to the next iteration*/





if(rev_sq == rev*rev)


printf("\n%d is Adams number",i);


}//end of for loop





}





int rev_number(int num)


{


int rev = 0;


while(num%10 !=0)


{


rev = rev + (num % 10) * 10;


num = num/10;


}


return rev;// returns the reverse


}//end of function





This program could be done with lot less variables.
Reply:I would loop through each number. In the loop:


1. convert number to string. Hold on to string and its reverse.


2. Square the number


3. convert the square to a string and reverse it.


4. Convert string to a number and get square root


5. Convert square root to string and compare to reverse of string in 1.





If they are equal, you have an adam number. Print it and move on to next number


If they are not, then move on to next number
Reply:Sounds to me like what you need to write, first, is a function which takes an int number, converts it to a string, reverses the string, then converts the reversed string into an integer for returning.





Then, you write a loop, from 10 to 100, in which the current index is passed to your function. That gives you the two values that have to prove to be an adam. Then you square both of those numbers. Then you need to compare the two squares to see if one is the reverse of the other. For that, you COULD use your function again on one of the two squares, then compare what is returned with what was generated.





Which class is this for - number theory? discrete math? Just curious. This kind of thing is so fun..





Too bad it has to be in C - in Perl or Tcl the code would be a lot simpler...

deliver flowers

No comments:

Post a Comment