声明
该系列文章来自:http://aperiodic.net/phil/scala/s-99/
大部分内容和原文相同,加入了部分自己的代码。
如有侵权,请及时联系本人。本人将立即删除相关内容。

P36 (**) Determine the prime factors of a given positive integer (2).

要求

Construct a list containing the prime factors and their multiplicity.

1
2
scala> 315.primeFactorMultiplicity
res0: List[(Int, Int)] = List((3,2), (5,1), (7,1))

Alternately, use a Map for the result.

1
2
scala> 315.primeFactorMultiplicity
res0: Map[Int,Int] = Map(3 -> 2, 5 -> 1, 7 -> 1)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package problem_31_to_40
class S99Int(val start: Int) {
import S99Int._
def primeFactorMultiplicity: Map[Int, Int] = {
def factorCount(n: Int, p: Int): (Int, Int) =
if (n % p != 0) (0, n)
else factorCount(n / p, p) match { case (c, d) => (c + 1, d) }
def factorsR(n: Int, ps: Stream[Int]): Map[Int, Int] =
if (n == 1) Map()
else if (n.isPrime) Map(n -> 1)
else {
val nps = ps.dropWhile(n % _ != 0)
val (count, dividend) = factorCount(n, nps.head)
Map(nps.head -> count) ++ factorsR(dividend, nps.tail)
}
factorsR(start, primes)
}
}

P37 (**) Calculate Euler’s totient function phi(m) (improved).

要求

See problem P34 for the definition of Euler’s totient function. If the list of the prime factors of a number m is known in the form of problem P36 then the function phi(m>) can be efficiently calculated as follows: Let [[p1, m1], [p2, m2], [p3, m3], …] be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula:

1
phi(m) = (p1-1)*p1^(m1-1) * (p2-1)*p2^(m2-1) * (p3-1)*p3^(m3-1) * ...

Note that a^b stands for the bth power of a.

代码

1
2
3
4
5
6
7
8
9
package problem_31_to_40
class S99Int(val start: Int) {
import S99Int._
def totient2: Int = start.primeFactorMultiplicity.foldLeft(1) { (r, f) =>
f match { case (p, m) => r * (p - 1) * Math.pow(p, m - 1).toInt }
}
}

P39 (*) A list of prime numbers.

要求

Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.

1
2
scala> listPrimesinRange(7 to 31)
res0: List[Int] = List(7, 11, 13, 17, 19, 23, 29, 31)

代码

  • (1):最简单最直观的方法就是遍历range,将是素数的留下来
1
2
3
4
5
6
7
8
object S99Int {
implicit def int2S99Int(i: Int): S99Int = new S99Int(i)
def listPrimesinRange(r: Range): List[Int] =
r.filter(_.isPrime).toList
}
  • (2):原作者用的方法,更加高效
1
2
3
4
5
6
7
8
9
10
object S99Int {
implicit def int2S99Int(i: Int): S99Int = new S99Int(i)
val primes = Stream.cons(2, Stream.from(3, 2) filter { _.isPrime })
def listPrimesinRange2(r: Range): List[Int] =
primes.dropWhile(_ < r.start).takeWhile(_ <= r.end).toList
}

P40 (**) Goldbach’s conjecture.

要求

哥德巴赫猜想

Goldbach’s conjecture says that every positive even number greater than 2 is the sum of two prime numbers. E.g. 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. It has been numerically confirmed up to very large numbers (much larger than Scala’s Int can represent). Write a function to find the two prime numbers that sum up to a given even integer.

1
2
scala> 28.goldbach
res0: (Int, Int) = (5,23)

代码

1
2
3
4
5
6
7
8
9
10
11
12
class S99Int(val start:Int) {
def goldbach: (Int, Int) = {
if (start <= 2 || (start & 1) == 1)
throw new UnsupportedOperationException("大于2的偶数才支持此操作")
primes.takeWhile(_ <= start)//可能的素数范围
.find(e => (start - e).isPrime) match {
case None => throw new IllegalArgumentException
case Some(x) => (x, start - x)
}
}
}

P41 (**) A list of Goldbach compositions.

要求

Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.

1
2
3
4
5
6
7
scala> printGoldbachList(9 to 20)
10 = 3 + 7
12 = 5 + 7
14 = 3 + 11
16 = 3 + 13
18 = 5 + 13
20 = 3 + 17

In most cases, if an even number is written as the sum of two prime numbers, one of them is very small. Very rarely, the primes are both bigger than, say, 50. Try to find out how many such cases there are in the range 2..3000.

Example (minimum value of 50 for the primes):

1
2
3
4
5
6
scala> printGoldbachListLimited(1 to 2000, 50)
992 = 73 + 919
1382 = 61 + 1321
1856 = 67 + 1789
1928 = 61 + 1867
The file containing the full class for this section is arithmetic.scala.

代码

  • (1) filter+foreach
1
2
3
4
5
6
7
8
9
10
object S99Int {
def printGoldbachList(r: Range): Unit = {
r.filter(e => e > 2 && (e & 1) == 0) //大于2的偶数
.foreach(e => {
val m = e.goldbach
println(e + " = " + m._1 + " + " + m._2)
})
}
}
  • (2) 原作者的做法
1
2
3
4
5
6
7
8
9
10
11
12
object S99Int {
def printGoldbachList(r: Range) {
printGoldbachListLimited(r, 0)
}
def printGoldbachListLimited(r: Range, limit: Int) {
(r filter { n => n > 2 && n % 2 == 0 } map { n => (n, n.goldbach) }
filter { _._2._1 >= limit } foreach {
_ match { case (n, (p1, p2)) => println(n + " = " + p1 + " + " + p2) }
})
}
}

附录–S99Int.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class S99Int(val start: Int) {
import S99Int._
def isPrime: Boolean =
(start > 1) && (primes.takeWhile(_ <= Math.sqrt(start)).forall(start % _ != 0))
def isCoprimeTo(x: Int): Boolean = gcd(start, x) == 1
def totient: Int = (1 to start).filter(start.isCoprimeTo(_)).length
def totient2: Int = start.primeFactorMultiplicity.foldLeft(1) { (r, f) =>
f match { case (p, m) => r * (p - 1) * Math.pow(p, m - 1).toInt }
}
def primeFactors: List[Int] = {
def primeFactorsR(x: Int, ps: Stream[Int]): List[Int] = {
x match {
//本身就是素数
case n if n.isPrime => List(n)
//能分解为n*ps.head
case n if (n % ps.head) == 0 => ps.head :: primeFactorsR(n / ps.head, ps)
//其他
case n => primeFactorsR(n, ps.tail)
}
}
return primeFactorsR(start, primes)
}
def primeFactorMultiplicity: Map[Int, Int] = {
def factorCount(n: Int, p: Int): (Int, Int) =
if (n % p != 0) (0, n)
else factorCount(n / p, p) match { case (c, d) => (c + 1, d) }
def factorsR(n: Int, ps: Stream[Int]): Map[Int, Int] =
if (n == 1) Map()
else if (n.isPrime) Map(n -> 1)
else {
val nps = ps.dropWhile(n % _ != 0)
val (count, dividend) = factorCount(n, nps.head)
Map(nps.head -> count) ++ factorsR(dividend, nps.tail)
}
factorsR(start, primes)
}
def goldbach: (Int, Int) = {
if (start <= 2 || (start & 1) == 1) throw new UnsupportedOperationException("大于2的偶数才支持此操作")
primes.takeWhile(_ <= start).find(e => (start - e).isPrime) match {
case None => throw new IllegalArgumentException
case Some(x) => (x, start - x)
}
}
}
object S99Int {
implicit def int2S99Int(i: Int): S99Int = new S99Int(i)
val primes = Stream.cons(2, Stream.from(3, 2) filter { _.isPrime })
def gcd(m: Int, n: Int): Int = if (n == 0) m else gcd(n, m % n)
def listPrimesinRange(r: Range): List[Int] =
r.filter(_.isPrime).toList
def listPrimesinRange2(r: Range): List[Int] =
primes.dropWhile(_ < r.start).takeWhile(_ <= r.end).toList
def printGoldbachList(r: Range): Unit = {
r.filter(e => e > 2 && (e & 1) == 0) //大于2的偶数
.foreach(e => {
val m = e.goldbach
println(e + " = " + m._1 + " + " + m._2)
})
}
}