Created
October 19, 2021 16:49
-
-
Save MartinRajniak/3ac7fd49e1b8583b7fd6a6d8525dd108 to your computer and use it in GitHub Desktop.
Sum of of all the multiples of 4 or 7 under 2500
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
println("Calculating using naive approach (in a loop).") | |
execute(::calculateSum) | |
println("Calculating using formula for AP series.") | |
execute(::calculateSumAP) | |
} | |
fun execute(calculateSum: (Long, Long, Long) -> Long) { | |
val testResult = calculateSum(4, 7, 10) | |
if (testResult != 19L) { | |
println("FAILED basic test: Sum of multiples of 4 or 7 under 10 is 19, but was $testResult") | |
return | |
} | |
val start = System.currentTimeMillis() | |
val first = 4L | |
val second = 7L | |
val limit = 2500L | |
val sum = calculateSum(first, second, limit) | |
println("Sum of all the multiples of $first or $second under $limit is $sum") | |
println("Time: ${System.currentTimeMillis() - start}") | |
} | |
fun calculateSum(first: Long, second: Long, limit: Long): Long { | |
val result = mutableSetOf(first, second) | |
for (number in 1 until limit) { | |
if (number % first == 0L || number % second == 0L) { | |
result += number | |
} | |
} | |
return result.sum() | |
} | |
fun calculateSumAP(first: Long, second: Long, limit: Long): Long { | |
return calculateSumAP(first, limit) + calculateSumAP(second, limit) - calculateSumAP(first * second, limit) | |
} | |
fun calculateSumAP(first: Long, limit: Long): Long { | |
// Number of multiples | |
val m = (limit - 1) / first | |
// sum of first m natural numbers | |
val sum = m * (m + 1) / 2 | |
// sum of multiples | |
return first * sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment