Palindromic Primes using Objective-C

I was watching the Data Structures course ware¬† at Academic Earth and there was a problem being solved to find all prime numbers within a range. It’s a very simple problem (not efficient) but I wanted to add some twist to it. So, I wrote a Prime number searcher which picks out only those that are Palindromic.


#import "Foundation/Foundation.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

  int counter = 0;
  int m = 100000;
  NSMutableString *s;

  for(int i=1; i<=m; i++){
    int flag = 0;
    int c = ceil(sqrt(i));
    for(int j = 2; j <= c; j++){       if( (i != 2) && (i % j) == 0){ 	flag =1; 	break;     }   }
      if(!flag){
         s = [NSMutableString stringWithFormat:@"%d", i];
         NSMutableString *ostr =  [NSMutableString stringWithCapacity:[s length] ];
         for(int x=([s length]-1); x>=0; x--){
            [ostr appendFormat:@"%C", [s characterAtIndex:x]];
         }
        if([s isEqualToString: ostr]){
          NSLog(@" %d is Palindromic Prime", i);
        }
  counter++;
}
}
  NSLog(@"A total of %d number of primes within %d", counter, m);
  [pool drain];
    return 0;
}

This entry was posted in Code, Objective-C. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>