While loop problem 1

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

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

2022-09-20 08:54

1 Answers

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 []


2022-09-20 08:54

If you have any answers or tips


© 2022 pinfo. All rights reserved.