ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# KiligWY's solution

## to Nth Prime in the Objective-C Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Given a number n, determine what the nth prime is.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself.

## Setup

There are two different methods of getting set up to run the tests with Objective-C:

• Create an Xcode project with a test target which will run the tests.
• Use the ruby gem `objc` as a test runner utility.

Both are described in more detail here: http://exercism.io/languages/objective-c

### Submitting Exercises

When submitting an exercise, make sure your solution file is in the same directory as the test code.

The submit command will look something like:

``````exercism submit <path-to-exercism-workspace>/objective-c/nth-prime/NthPrime.m
``````

You can find the Exercism workspace by running `exercism debug` and looking for the line beginning with Workspace.

## Source

A variation on Problem 7 at Project Euler http://projecteuler.net/problem=7

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### NthPrimeTest.m

``````#import <XCTest/XCTest.h>

#if __has_include("BobExample.h")
# import "NthPrimeExample.h"
#else
# import "NthPrime.h"
#endif

NS_ASSUME_NONNULL_BEGIN

@interface NthPrimeTest : XCTestCase

@end

@implementation NthPrimeTest

- (void)testFirstPrime {
int primeNum = 1;
int expected = 2;
XCTAssertEqual(expected, result);
}

- (void)testSecondPrime {
int primeNum = 2;
int expected = 3;
XCTAssertEqual(expected, result);
}

- (void)testSixthPrime {
int primeNum = 6;
int expected = 13;
XCTAssertEqual(expected, result);
}

- (void)testBigPrime {
int primeNum = 10001;
int expected = 104743;
XCTAssertEqual(expected, result);
}

- (void)testZeroPrime {
int primeNum = 0;
int expected = 0;
XCTAssertEqual(expected, result);
}

@end
NS_ASSUME_NONNULL_END``````

### NthPrime.h

``````#import <Foundation/Foundation.h>

@interface NthPrime : NSObject

@end``````

### NthPrime.m

``````#import "NthPrime.h"

@implementation NthPrime

if (number == 0) {
return 0;
}
if (number == 1) {
return 2;
}
if (number == 2) {
return 3;
}
int index = 2;
int result = 0;
for (int i = 5; ; i += 2) {
BOOL isPrime = YES;
for (int j = 3; j < i; j +=2) {
if (i % j == 0) {
isPrime = NO;
break;
}
}
if (isPrime) {
result = i;
index++;
if (index == number) {
break;
}
}
}
return result;
}

@end``````