Reputation: 73
I am writing a recursive function to check if a non-negative Integer is Prime in SCALA. My function takes two inputs to do so. Here is my code:
import io.StdIn._
def isPrime (x:Int, i:Int): Boolean = {
if (i < 3) {
true
}else if (x % i == 0) {
false
}else{
isPrime(x,i-1)
}
}
print("Enter a number to check if it is a prime number: " )
val num1 = readInt()
println(isPrime(num1,num1-1))
My question is that is there a way for me to take one input as the parameter for the function? The code has to use a recursive function. I know that there are more effective ways to check if a number is prime (using iteration perhaps), but I'm just doing this as a practice problem.
Upvotes: 1
Views: 572
Reputation: 12102
One option is to make an inner method
def isPrime(x:Int): Boolean = {
def loop(i: Int): Boolean =
if (i<3 ) {
true
} else if (x % i==0) {
false
} else {
isPrime(x,i-1)
}
loop(x, x - 1)
}
another option is to make a default parameter. Those can't refer back to the previous parameter, so you'll have to use a workaround. Here I pass some j
, and make i = x - j
, so I can just increment j
starting from 1
def isPrime(x: Int, j: Int = 1): Boolean = {
val i = x - j
if (i < 3) {
true
} else if (x % i==0) {
false
} else {
isPrime(x, j + 1)
}
}
Unrelatedly, there is a bug in your code: 4 should not be prime.
Upvotes: 1
Reputation: 1725
It is perfectly fine, I'd say even standard practice, to wrap recursive functions with a calling function. For example:
def isPrime( x:Int ) = {
def recIsP( n:Int, i:Int ) : Boolean = i == n || n % i != 0 && recIsP(n, i + 1)
recIsP(x,2)
}
isPrime(3301)
Upvotes: 1