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

    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,612评论 5 471
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,345评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,625评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,022评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,974评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,227评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,688评论 3 392
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,358评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,490评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,402评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,446评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,126评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,721评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,802评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,013评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,504评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,080评论 2 341

推荐阅读更多精彩内容

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