 # wuzehua's solution

## to Nth Prime in the Swift Track

Published at Mar 18 2020 · 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

Go through the project setup instructions for Xcode using Swift:

http://exercism.io/languages/swift
http://exercism.io/languages/swift/tests

Notably from the source directory:

`swift test` runs tests
`swift package generate-xcodeproj` creates an Xcode project

## 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.

### LinuxMain.swift

``````import XCTest
@testable import NthPrimeTests

XCTMain([
testCase(NthPrimeTests.allTests),
])``````

### NthPrimeTests.swift

``````import XCTest
@testable import NthPrime

class NthPrimeTests: XCTestCase {
func testFirst() {
XCTAssertEqual(2, Prime.nth(1))
}

func testSecond() {
XCTAssertEqual(3, Prime.nth(2))
}

func testSixthPrime() {
XCTAssertEqual(13, Prime.nth(6))
}

func testBigPrime() {
XCTAssertEqual(104_743, Prime.nth(10_001))
}

func testWeirdCase() {
XCTAssertNil(Prime.nth(0))
}

static var allTests: [(String, (NthPrimeTests) -> () throws -> Void)] {
return [
("testFirst", testFirst),
("testSecond", testSecond),
("testSixthPrime", testSixthPrime),
("testBigPrime", testBigPrime),
("testWeirdCase", testWeirdCase),
]
}
}``````
``````//Solution goes in Sources
class Prime{

static func nth(_ n: Int) -> Int?{
if n <= 0{
return nil
}

var i = 0
var num = 2
var result = 2
while true{
if isPrime(num){
i += 1
if i == n{
result = num
break
}
}

num += 1
}

return result
}

static func isPrime(_ value: Int) -> Bool {
if value <= 1 {
return false
}

if value == 2 || value == 3 {
return true
}

var i: Int = 2
var flag = true
let sqrt = Int(Double(value).squareRoot())
while i <= sqrt {
if value % i == 0 {
flag = false
break
}

i += 1
}

return flag
}
}``````