How i can migrate my getPrime() method so it only returns me prime number but not ()

岁酱吖の 提交于 2021-02-10 06:33:12

问题


Problem : I just want to call getPrime(100) and return only the prime numbers and I don't want use collect.

def main(args: Array[String]){
  getPrime(100).collect{
    case i:Int => println(i);
  }
}

Here I want to change something

def getPrime(range : Int) = {
  Range(2,range).map(x => if(isPrime(x)) x);
}

def isPrime(no : Int) = !Range(2,Math.sqrt(no).toInt + 1).exists(x => no%x ==0)

回答1:


As has already been pointed out, you don't want to use if without an else, and you shouldn't use map() when what you need is filter()

def getPrime(range: Int): Seq[Int] =
  Range(2,range).filter(isPrime)

isPrime() can also be expressed a little more directly.

def isPrime(n: Int): Boolean =
  2 to Math.sqrt(n).toInt forall(n%_ > 0)



回答2:


If you don't want to use collect, you can use isInstanceOf to filter out only Int values,

def getPrime(range: Int) = {
      Range(2, range).map(x => if (isPrime(x)) x).filter(_.isInstanceOf[Int])
    }



回答3:


Basically, your getPrime method is returning AnyVal. You can use collect there to return only collection of int.

    scala> def getPrime(range : Int) = {
     |       Range(2,range).map(x => if(isPrime(x)) x).collect{
     | case e:Int => e
     |   }
     | }
getPrime: (range: Int)scala.collection.immutable.IndexedSeq[Int]

scala> getPrime(100)
res8: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)



回答4:


Another great way to generate prime numbers would be to use streams.

Consider the following

def naturals(n: Int): Stream[Int] = n #:: naturals(n + 1)
def primes(s: Stream[Int] = naturals(2)): Stream[Int] = s.head #:: primes(s.tail.filter(_ % s.head > 0))

That's it. You have a very elegant functional prime number generator.

If you want the first 100 prime numbers as a list

primes().take(100).toList

Or if you are interested only in the 100th prime number

primes().drop(99).head

This was the example that sold me on the usefulness of streams !



来源:https://stackoverflow.com/questions/49644062/how-i-can-migrate-my-getprime-method-so-it-only-returns-me-prime-number-but-no

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!