Skip to content

Instantly share code, notes, and snippets.

@andrewgazelka
Created February 28, 2019 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgazelka/15b95a2f5ace938cee9d9228b2f193bb to your computer and use it in GitHub Desktop.
Save andrewgazelka/15b95a2f5ace938cee9d9228b2f193bb to your computer and use it in GitHub Desktop.
fun productSumFactors(max: Int) = sequence {
val size = log2(max.toDouble()).toInt() + 1
val array = List(size) { 1 }.toIntArray()
while (true) {
var indexOn = array.size - 1
array[indexOn]++
var reduced: Int
while (array.reduce { acc, i -> acc * i }.also { reduced = it } > max) {
indexOn--
if (indexOn < 0) return@sequence
val nextIndex = array[indexOn]++
array[indexOn + 1] = nextIndex
}
val sum = array.sum()
val k = size + (reduced - sum)
yield(FactorResult(k, reduced))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment