Skip to content

Instantly share code, notes, and snippets.

@GuanshanLiu
Created May 10, 2016 05:59
Show Gist options
  • Save GuanshanLiu/3c2ef4aaaf97c2f2eb87d2afa8a15923 to your computer and use it in GitHub Desktop.
Save GuanshanLiu/3c2ef4aaaf97c2f2eb87d2afa8a15923 to your computer and use it in GitHub Desktop.
Project Euler in Swift #1 for Medium
let filtered = (1..<1000).filter {
$0 % 3 == 0 || $0 % 5 == 0
}
filtered.reduce(0, combine: +)
extension Int {
func divisibleBy(num: Int) -> Bool {
return num % self == 0
}
}
func satisfyOne<T>(target: T, rules: [T -> Bool]) -> Bool {
for rule in rules {
if rule(target) {
return true
}
}
return false
}
func sumOfMultiples(numbers: [Int], divisibles: [Int -> Bool]) -> Int {
return numbers.filter { satisfyOne($0, rules: divisibles) }.reduce(0, combine: +)
}
sumOfMultiples(Array(1..<1000), divisibles: [3.divisibleBy, 5.divisibleBy])
sumOfMultiples(Array(1..<1000), divisibles: [3.divisibleBy, 5.divisibleBy, 7.divisibleBy])
func sumOfMultiples(max: Int, divisor: Int) -> Int {
let n = max / divisor
return n * (n + 1) / 2 * divisor
}
func sumOfMultiples(max: Int, divisor1: Int, divisor2: Int) -> Int {
return sumOfMultiples(max, divisor: divisor1)
+ sumOfMultiples(max, divisor: divisor2)
- sumOfMultiples(max, divisor: divisor1 * divisor2)
}
sumOfMultiples(999, divisor1: 3, divisor2: 5)
let max = 999
sumOfMultiples(max, divisor: 3) + sumOfMultiples(max, divisor: 5) + sumOfMultiples(max, divisor: 7) - sumOfMultiples(max, divisor: 15) - sumOfMultiples(max, divisor: 21) - sumOfMultiples(max, divisor: 35) + sumOfMultiples(max, divisor: 105)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment