Joseph Jude

Technology, Psychology, and Story Telling

Swift Challenge 001: Divisible by 7 but not a multiple of 5

Posted: Tags: code,swift

Challenge: Write a program to find all numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line.

Logic: Both of these can be computed by modulo division. If a number is divisible by 7, modulo division will return 0; if a number is not a multiple, then it will not return 0.

Code:

var output: [Int] = []
for i in 2000...3200{
  if (i % 7 == 0) && (i % 5 != 0){
    output.append(i)
  }
}

var outInString = output.map(){ String($0) }
print(outInString.joinWithSeparator(","))

Uses:

  • declaring int empty array
  • range
  • modulo division
  • append to array
  • convert int to string
  • map
  • join elements of array with a separator

Clone Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.


Comments

comments powered by Disqus