Files
FunProg-Scala/src/FinalPrep1/Ex2.sc

18 lines
640 B
Scala

import scala.math.{ceil, min, sqrt}
def fourSquares(n: Int): List[Tuple4[Int, Int, Int, Int]] = {
val tups = for (
d: Int <- ceil(sqrt(n)).toInt to 0 by -1;
c: Int <- min(d, ceil(sqrt(n - d*d))).toInt to 0 by -1;
b: Int <- min(c, ceil(sqrt(n - d*d - c*c))).toInt to 0 by -1;
a: Int <- min(b, ceil(sqrt(n - d*d - c*c - b*b))).toInt to 0 by -1
if (a*a + b*b + c*c + d*d == n)
) yield Tuple4(a, b, c, d)
tups.toList
}
fourSquares(0) // List(Tuple4(0, 0, 0, 0))
fourSquares(3) // List(Tuple4(0, 1, 1, 1))
fourSquares(15) // List(Tuple(1, 1, 2, 3))
fourSquares(88) // List(Tuple4(0, 4, 6, 6), Tuple4(2, 2, 4, 8))