// By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. // // What is the 10 001st prime number? // // Note: this is not meant to be the most efficient solution, primarily as an example written in Objective-C. #import <Foundation/Foundation.h> NSInteger prime(NSInteger number) { // prime numbers are only divisble by itself and one // Steps // 1. if 'n' is divisble by 2 it is not a prime // 2. if 'n' is divisble by 3 it is not a prime // 3. divide by each number between 2 and n^1/2 inclusive NSMutableArray *primes; // an array to contain prime numbers (not necessary, but it's nice to have them) primes = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInteger:2], [NSNumber numberWithInteger:3] , nil]; // 2 and 3 are base cases so we will manually add these values NSInteger primeCheckValue = 4; // we will start checking for primes at number 4 BOOL isPrime = false; // this will be set to 'true' when a prime has been found and reset to false at the start of the loop while (primes.count < number) { if (primeCheckValue % 2 == 0 || primeCheckValue % 3 == 0) { // Step 1 and 2 isPrime = false; } else { for (NSInteger i = 2; i <= sqrt(primeCheckValue); i++) { // Step 3 if (primeCheckValue % i == 0) { isPrime = false; break; } else { isPrime = true; } } } if (isPrime == true) { [primes addObject:[NSNumber numberWithInteger:primeCheckValue]]; isPrime = false; } primeCheckValue++; } return [[primes objectAtIndex:number-1] integerValue]; } int main(int argc, const char * argv[]) { @autoreleasepool { NSLog(@"%ld", (long)prime(10001)); // Output: 104743 } return 0; }