Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find prime numbers using Scala. Help me to improve

I wrote this code to find the prime numbers less than the given number i in scala.

def findPrime(i : Int) : List[Int] = i match {
    case 2 => List(2)
    case _ => {
    val primeList = findPrime(i-1)
    if(isPrime(i, primeList)) i :: primeList else primeList
    }
}

def isPrime(num : Int, prePrimes : List[Int]) : Boolean = prePrimes.forall(num % _ != 0)    

But, I got a feeling the findPrime function, especially this part:

case _ => {
    val primeList = findPrime(i-1)
    if(isPrime(i, primeList)) i :: primeList else primeList
}

is not quite in the functional style.

I am still learning functional programming. Can anyone please help me improve this code to make it more functional.

Many thanks.

like image 798
Kevin Avatar asked Mar 14 '12 23:03

Kevin


People also ask

How to check if a number is prime or not in Scala?

def isPrime (num:Int):Boolean = (num > 1) && ! (2 to scala.math.sqrt (num).toInt).exists (x => num % x == 0) In the second line, I found any number from 1 to num/2, divides the given number. If yes that means it is not prime. For example, 10 -> It will check 2 to 3 and 2 will divide 10 so this is not prime.

How to find the sum of prime numbers in Python?

# To find the sum of prime number in python form range 2 to n. # Defining the function defSum_Of_Primes(n):# creating a list to store the prime numbersprime = [True] * (n + 1) # We have created a boolean array "prime[0..n]". # We initialize all the entries as true.

How to compute the prime numbers?

T he Sieve Eratosthenes is one of the oldest and perhaps simplest ways known to compute the prime numbers. The algorithm is as follows: Start with a prime number and eliminate all multiples of it Find the first number not eliminated, mark it as prime

How do you prove that a factorial mod is prime?

You can also use Wilson's theorem. p is prime if (p-1)! = -1 mod p. Normally computing (p-1)! is expensive as the number becomes huge, but computing the factorial mod p is less than p.


1 Answers

Here's a functional implementation of the Sieve of Eratosthenes, as presented in Odersky's "Functional Programming Principles in Scala" Coursera course :

  // Sieving integral numbers
  def sieve(s: Stream[Int]): Stream[Int] = {
    s.head #:: sieve(s.tail.filter(_ % s.head != 0))
  }

  // All primes as a lazy sequence
  val primes = sieve(Stream.from(2))

  // Dumping the first five primes
  print(primes.take(5).toList) // List(2, 3, 5, 7, 11)
like image 162
Rahel Lüthy Avatar answered Oct 04 '22 07:10

Rahel Lüthy