objective c - Find the 42th number which sum of its digits is 42 -
i've got interesing programming/mathematical problem. want write application, find 42th number sum of digits 42, need find number have sum of digits 42 , add new array print 42th number in new array have 50 numbers have sum of digits 42. thank taking time help.
@implementation appdelegate
static nsarray *newarray ; - (void)applicationdidfinishlaunching:(nsnotification *)anotification { int numberwithsum42; (int i=69999;i<80000;i++) { int x=[self findtotalnumber:i]; if(x==12){ numberwithsum42=i; newarray = [nsarray arraywithobjects:[nsnumber numberwithint:numberwithsum42], nil]; } nslog(@"%@",newarray); } [self print42ndvariable]; } -(void)print42ndvariable{ int j; int count = (int)[newarray count]; (j = 0; j < count; j++){ nslog (@"42nd variable of array = %@", [newarray objectatindex: 42]); } } -(int)findtotalnumber:(int) n{ int s=0; while (n>0) { int k=n%10; s=s+k; n=n/10; } nslog(@"%i",s); return n; }
@end
- (void)applicationdidfinishlaunching:(nsnotification *)anotification{ int requirednumber; int currentindex; int sumofdigits; //assuming limits wnat 69000<=x<80000 (int i=69999;i<80000;i++) { sumofdigits= [self sum:i]; if(i==42){ currentindex++; } if (currentindex == 42){ nslog(i); //the number! } } } -(void)sum:(int)number{ int digit,sum=0, temp; temp = number; while(temp > 0) { digit = temp%10; sum += digit; temp = temp/10; } nslog(@"sum of digits of %i = %i",number,sum); return sum; }
Comments
Post a Comment