scala-problem36-40

[TOC]

** 声明**
该系列文章来自: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.

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

Alternately, use a Map for the result.

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

代码

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:

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.

代码

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.

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

代码

  • (1):最简单最直观的方法就是遍历range,将是素数的留下来
object S99Int {

    implicit def int2S99Int(i: Int): S99Int = new S99Int(i)

    def listPrimesinRange(r: Range): List[Int] =
        r.filter(_.isPrime).toList

}
  • (2):原作者用的方法,更加高效
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.

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

代码

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.

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):

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
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) 原作者的做法
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

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)
            })

    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,404评论 0 23
  • Node.js 路由我们要为路由提供请求的URL和其他需要的GET及POST参数,随后路由需要根据这些数据来执行相...
    yyshang阅读 1,846评论 0 1
  • 有时候,我们爱一件事物,却不能好好对待它,我们哀叹它的式微,却从未用我们的想法去拯救它,不要只是热爱,要去做......
    为心修行阅读 1,547评论 0 0
  • 茫茫人海 你在哪里 我找不到 浩浩宇袤 你在哪里 我发现不了 所有的谎言 也成了谜语 而我的静默 凝固了空气 爱恋...
    怡馨宅阅读 1,111评论 7 10
  • 我的脑子被僵尸吃掉了,知道这个事实的时候,我正在大街上闲逛。 我是一个宅男哎!他妈的我在大街上这是干啥。这么想着,...
    老愤青阅读 4,572评论 0 0