patternMinor
Find next prime
Viewed 0 times
primenextfind
Problem
I wrote small app finding next prime number starting from number passed as argument:
Is there better (more functional way) to wrote
object HelloWorld extends App {
println(findNextPrime(49));
def findNextPrime(n: Int) : Int = {
var m = n;
while(true){
m += 1;
if(isPrime(m)){
return m;
}
}
throw new Exception("Something went wrong.");
}
def isPrime(n: Int): Boolean = {
n match {
case 0|1 => return false
case 2|3 => return true
case _ => {
(2 to Math.sqrt(n).toInt).forall(y => n%y!=0)
}
}
}
}Is there better (more functional way) to wrote
findNextPrime in Scala ?Solution
With the exception of the number 2, the next prime number will not be 1 away from the number that you have entered, so this can be amended:
to something like:
I'm not sure about the exact Scala syntax, nor do I know the probability of the next prime number being n+2, but this will reduce the number of calls to your
I've corrected the logic to account for positive even numbers been entered. Once it hits an odd number then it will add 2. This will need testing and debugging. The m%2 is modulo in C and C-based languages; not sure if this is correct for Scala.
m += 1;to something like:
if(m == 2){
m += 1;
}else if(m >= 3 && m%2 == 1){
m += 2;
}else if(m >= 3 && m%2 == 0){
m += 1;
}else{
// Number is not prime
}I'm not sure about the exact Scala syntax, nor do I know the probability of the next prime number being n+2, but this will reduce the number of calls to your
isPrime() method which will make your program more efficient.I've corrected the logic to account for positive even numbers been entered. Once it hits an odd number then it will add 2. This will need testing and debugging. The m%2 is modulo in C and C-based languages; not sure if this is correct for Scala.
Code Snippets
if(m == 2){
m += 1;
}else if(m >= 3 && m%2 == 1){
m += 2;
}else if(m >= 3 && m%2 == 0){
m += 1;
}else{
// Number is not prime
}Context
StackExchange Code Review Q#154991, answer score: 3
Revisions (0)
No revisions yet.