Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant variable value on a recursive function

static boolean isPrime(int num){
    int consNum = num; //something like having a non-changing value 

    if(consNum < 2){
        return false;
    }

    else if( consNum % Math.round(num--/2) == 0 && num > 2)
        return false;
    }

    else{
        if(num==1)
            return true;
        else
            return isPrime(num);
    }

}

I'm trying to create a function that will determine if num is a prime number. Problem, i want a value(consNum) to stay with that value during the first call, Is there a way to do this recursively?

Edit

from:

if( (consNum % (int)(num--/2) + 0.5 == 0 ) 

to:

if( (consNum % Math.round(num--/2) == 0 && num > 2) 

1 Answers

Local variables are local to the invocation of the particular method; recursive methods are no exception.

If you wish to pass that value down the invocation chain, you need to make a second parameter for it, and pass it down explicitly:

// Users of your code invoke this method
public static boolean isPrime(int num) {
    return isPrime(num, num);
}
// This overload with two parameters is the actual recursive method
private static boolean isPrime(int num, int original) {
    if(original%(int)((num--/2)+0.5)==0)
        return false;
    }

    else{
        if(num==1)
            return true;
        else
            return isPrime(num, original);
    }
}
like image 112
Sergey Kalinichenko Avatar answered Jul 06 '26 18:07

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!