-
Notifications
You must be signed in to change notification settings - Fork 2
/
IntegerGeneratorsMath.scala
60 lines (49 loc) · 1.8 KB
/
IntegerGeneratorsMath.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package integerOperations
import utils.InputException
import utils.ExceptionMessages.NegativeInput
import integerOperations.IntegerProperties._
import scala.annotation.tailrec
import scala.util.{Failure, Success, Try}
/**
* Contains generators, that use more specific math or algorithms.
*
* Purity project by Daniil Tekunov.
*/
class IntegerGeneratorsMath(val til: Int) {
import IntegerGeneratorsMath._
/**
* Generates prime numbers using Sieve of Eratosthenes.
*/
def generateEratosthenesPrimes: List[Int] =
Try(generateEratosthenesPrimesLogic(Stream.from(2)).take(til)) match {
case Success(something) => something.toList
case Failure(ex) => throw new InputException(ex.toString)
}
/**
* Sub-function for generateEratosthenesPrimes
*/
private def generateEratosthenesPrimesLogic(input: Stream[Int]): Stream[Int] =
input.head #:: generateEratosthenesPrimesLogic(input.tail.filter(_ % input.head != 0))
/**
* Generates Fermat numbers in range from 1 to until.
*/
def generateFermatNumbers: List[Int] = Try(generateFermatNumbersLogic()) match {
case Success(something) =>
if (something == List(3)) something
else something.tail
case Failure(ex) => throw new InputException(ex.toString)
}
/**
* Sub-function for generateFermatNumbers
*/
@tailrec
private def generateFermatNumbersLogic(outcomeList: List[Int] = List(3), cur: Int = 3): List[Int] = {
if (til < 3) throw new InputException("\"generateCatalanNumbers\" " + NegativeInput)
else if (til < 5) List(3)
else if (outcomeList.last > til) outcomeList.init
else generateFermatNumbersLogic(outcomeList :+ cur, (cur - 1).sqr + 1)
}
}
object IntegerGeneratorsMath {
implicit def intToGenerators(a: Int): IntegerGeneratorsMath = new IntegerGeneratorsMath(a)
}