0%

21 Swift Task

1
2
3
4
5
6
func plusOne(to number: Int) -> Int { number * (number + 1) / 2 }

plusOne(to: 10)
// 55
plusOne(to: 100)
// 5050

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func ifNumberHasThreeSixNinePrintAsteriskFromOne(to here: UInt) {

for number in 1 ... here {
let hasThreeSixNine = String(number).contains("3") || String(number).contains("6") || String(number).contains("9")

if hasThreeSixNine { print("*", terminator: " ") } else { print(number, terminator: " ") }
}
print("")
}

ifNumberHasThreeSixNinePrintAsteriskFromOne(to: 10)
// 1 2 * 4 5 * 7 8 * 10
ifNumberHasThreeSixNinePrintAsteriskFromOne(to: 23)
// 1 2 * 4 5 * 7 8 * 10 11 12 * 14 15 * 17 18 * 20 21 22 *

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
func getGreastCommonDivisorAndLeastCommonMultiple(firstNumber: Int, secondNumber: Int) -> Dictionary<String, Int> {

var greastCommonDivisorAndLeastCommonMultiple = Dictionary<String, Int>()

func getGreastCommonDivisor(_ m: Int, _ n: Int) -> Int {
var a: Int = 0
var b: Int = max(m, n)
var r: Int = min(m, n)

while r != 0 {
a = b
b = r
r = a % b
}

return b
}

func getLeastCommonMultiple(_ m: Int, _ n: Int) -> Int {
m * n / getGreastCommonDivisor(m, n)
}

greastCommonDivisorAndLeastCommonMultiple.updateValue(getGreastCommonDivisor(firstNumber, secondNumber), forKey: "Greatest Common Divisor")
greastCommonDivisorAndLeastCommonMultiple.updateValue(getLeastCommonMultiple(firstNumber, secondNumber), forKey: "Least Common Multiple")

return greastCommonDivisorAndLeastCommonMultiple
}

getGreastCommonDivisorAndLeastCommonMultiple(firstNumber: 140, secondNumber: 72)
// ["Greatest Common Divisor": 4, "Least Common Multiple": 2520]
getGreastCommonDivisorAndLeastCommonMultiple(firstNumber: 85, secondNumber: 500)
//["Greatest Common Divisor": 5, "Least Common Multiple": 8500]