added final exam preparation

This commit is contained in:
2025-05-19 22:06:05 +02:00
parent 5365eabadd
commit ec0e1e8ae4
4 changed files with 212 additions and 0 deletions

18
src/FinalPrep1/Ex2.sc Normal file
View File

@ -0,0 +1,18 @@
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))