Create function multiplies_of_k(n,k), in which n and k are two integers larger than 0. The function will return a list, which contains all the multiplies of k not larger than n in ascending order. k, 2k, 3k, .., mk.
Example: multiplies_of_k(30, 7) => [7 ,14, 21, 28]
while-loop
func multiples_of_k(_ n: Int, _ k: Int) -> [Int] {
guard n >= k else { return [] }
return (1...(n / k)).map { $0 * k }
}
for (n, k) in [(30, 7), (5, 3), (1, 10)] {
print(n, k, multiples_of_k(n, k))
}
➜ swift multiples_of_k.swift
30 7 [7, 14, 21, 28]
5 3 [3]
1 10 []
© 2024 OneMinuteCode. All rights reserved.