Last active
April 6, 2019 14:08
-
-
Save 2efPer/a0c2f8b44f4194eb7417bb6518e01d02 to your computer and use it in GitHub Desktop.
EulerProject.scala
This file contains hidden or 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
| //1 | |
| (1 to 1000).filter(x => x%3==0 || x%5==0).sum | |
| //2 | |
| def fib: Stream[Long] = { | |
| def tail(h: Long, n: Long): Stream[Long] = h #:: tail(n, h + n) | |
| tail(0, 1) | |
| } | |
| //3 Largest prime factor | |
| object Euler03 { | |
| type Factor = Long | |
| type Number = Long | |
| type Factors = List[Factor] | |
| /* Returns the largest prime factor of the given | |
| * number.It first computes all the prime factors of the given | |
| * number and then returns the largest among them. | |
| */ | |
| def largestPrimeFactor (x: Number): Factor = | |
| primeFactors(x).max | |
| /* Returns the prime factors of the given number x. For instance | |
| * if the number x equals to 5, it returns List(2,3). | |
| */ | |
| def primeFactors(x: Number): Factors = { | |
| val numUpToSqrt = (2L to math.sqrt(x).toLong) | |
| val divisibleBy = numUpToSqrt.find(x % _ == 0) | |
| divisibleBy match { | |
| case None => List(x) | |
| // x is a prime number and not divisible by any | |
| case Some(d) => d :: primeFactors(x/d) | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment