Navin Gelot
Navin Gelot

Reputation: 1334

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

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)

Upvotes: 2

Views: 214

Answers (4)

Utsav
Utsav

Reputation: 566

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 !

Upvotes: 0

jwvh
jwvh

Reputation: 51271

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)

Upvotes: 1

Mahesh Chand
Mahesh Chand

Reputation: 3250

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)

Upvotes: 0

vindev
vindev

Reputation: 2280

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

Upvotes: 0

Related Questions