Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a number is prime in Scala

Tags:

scala

I wanted to check if a number is prime or not. I wrote the following code, but it does not return any value:

 def isprime(x:Int) = {
     | if (x==1) false
     | else {
     | for (i <- 2 to x-1) {
     | if (x % i == 0) false
     | else true
     | }
     | }
     | }
like image 246
Arnab Avatar asked Apr 27 '16 06:04

Arnab


People also ask

How do you check if a number is a prime number?

To prove whether a number is a prime number, first try dividing it by 2, and see if you get a whole number. If you do, it can't be a prime number. If you don't get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11 (9 is divisible by 3) and so on, always dividing by a prime number (see table below).

How do you check if a number is prime in an array?

To check prime numbers, we declare a function isPrime() that will return 1, if number is prime and return 0 if number is not prime.


1 Answers

What you did is a called defining a function so obviously it won't return anything and as a matter of fact, this function returns AnyVal which obviously won't help you much. I suspect that you actually need a Boolean type returned.

Since you are working with the REPL, you would want to define your function to check if a number is prime. I called it isPrime2 and then test it.

def isPrime2(i :Int) : Boolean = {
|     if (i <= 1)
|       false
|     else if (i == 2)
|       true
|     else
|       !(2 to (i-1)).exists(x => i % x == 0)
|   }
// isPrime2: (i: Int)Boolean

(1 to 10).foreach(i => if (isPrime2(i)) println("%d is prime.".format(i)))
// 2 is prime.
// 3 is prime.
// 5 is prime.
// 7 is prime.

I would even suggest a simpler version if you care not using if else conditions :

def isPrime1(n: Int): Boolean = ! ((2 until n-1) exists (n % _ == 0))

Which also returns a Boolean.

EDIT:

As @TheArchetypalPaul stated, which was also implied, the problem is that your for loop isn't resulting in any value - you calculate a true/false value, but then don't do anything with it. So your else clause doesn't result in any value (in fact, it produces Unit). You need to return false as soon as you find a divisor - and the way to do that is probably exists as in isPrime1.

like image 58
eliasah Avatar answered Sep 18 '22 21:09

eliasah