Mathematics 1

-

3 min readMay 31, 2018

--

4. 1. Permutation

func perm(_ array:[Int],_ depth:Int,_ n:Int,_ k:Int) {
var array = array

if depth == k {
print(array)
} else {
for i in depth ..< n {
//SWAP 1
(array[i],array[depth]) = (array[depth],array[i])

//Resursion
perm(array, depth + 1, n, k)

//SWAP 2
(array[i],array[depth]) = (array[depth],array[i])
}
}
}

4. 2. Combination

Combinations: Unordered lists

func combination(_ array:[Int],_ index:Int,_ n:Int,_ r:Int,_ target:Int) {
var array = array

if (r == 0) {
print(array[0..<index])
} else if target != n {
array[index] = target
combination(array, index + 1, n, r - 1, target + 1)
combination(array, index, n, r, target + 1)
}
}
combination([0,1,2,3,4], 0, 5, 3, 0)

4. 3. Prime Number

  • If num is divided by i, it is not a prime number.
  • If it divided, escape the loop
  • divide the prime number smaller than the input number
func getPrime(_ num:Int) {   
var prime:[Int] = [2]

for i in 2...num {
for j in 0 ..< prime.count {
// Not a prime number
if i % prime[j] == 0 {
break
} else if j + 1 == prime.count { // it is prime number
prime.append(i)
}
}
}
print(prime)
}
getPrime(10)

4. 4. Eratostheneen seula

Let’s say you want to find all prime number to 120.

After putting them all in the array from 2 to 120, check everything that is not a prime number.
Check all multiples of 2 except 2.
Check all multiples of 3 except 3.
4 is skip because it was checked before.
Check for multiples of all 5 except 5. … …
There are prime numbers of unchecked numbers.

When checking, use the loop only as many times as you want to check without having to check all the numbers. And does not find a multiple of the number already checked to zero. Because the multiples of the checked number are already checked.

func getPrimeNumberEratostheneen(_ num:Int) -> [Int] {
var array = [Int]()
var result = [Int]()

//init the array
for i in 0...num {
array.append(i)
}

for i in 2...num {
if array[i] != 0 {
var j = i + i
while j <= num {
array[j] = 0
j += i
}
}
}

for i in 2...num {
if array[i] != 0 {
result.append(i)
}
}

return result
}
print(getPrimeNumberEratostheneen(100))

4. 5. GCD Euclideon Algorithm

func GCD(_ n:Int,_ m:Int) -> Int {
if n > m {
if (n % m == 0) {
return m
} else {
return GCD(m, n % m)
}
} else {
if (m % n == 0) {
return n
} else {
return GCD(n, m % n)
}
}
}
GCD(25,3)

--

--