Proper divisors: Difference between revisions

(Scala solution)
Line 865:
 
=={{header|Scala}}==
 
==Simple proper divisors==
<lang Scala>def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
def format(i: Int, divisors: Seq[Int]) = f"$i%5d ${divisors.length}%2d ${divisors mkString " "}"
Line 893 ⟶ 895:
15120 79
18480 79</pre>
 
==Proper divisors for big (long) numbers==
<lang Scala>import annotation.tailrec
import collection.parallel.mutable.ParSeq
 
def factorize(n: Long): List[Long] = {
@tailrec
def factors(tuple: (Long, Long, List[Long], Int)): List[Long] = {
tuple match {
case (1, _, acc, _) => acc
case (n, k, acc, _) if (n % k == 0) => factors((n / k, k, acc ++ ParSeq(k), Math.sqrt(n / k).toInt))
case (n, k, acc, sqr) if (k < sqr) => factors(n, k + 1, acc, sqr)
case (n, k, acc, sqr) if (k >= sqr) => factors((1, k, acc ++ ParSeq(n), 0))
}
}
factors((n, 2, List[Long](), Math.sqrt(n).toInt))
}
def properDivisors(n: Long) = {
val factors = factorize(n)
val products = (1 until factors.length).map(i =>
factors.combinations(i).map(_.product).toList).flatten
(1L +: products).filter(_ < n)
}</lang>
 
=={{header|Swift}}==
Anonymous user