3) Consider the following JAVA method. This method receives an integer and then
ID: 3733198 • Letter: 3
Question
3) Consider the following JAVA method. This method receives an integer and then returns true or false. Suppose we call this method as follows:
boolean x = prm(25);
boolean y = prm(17);
What would be “x” and “y” after calling the method? Trace the code and show the result step-by-step.
public static boolean prm(int n)
{
if (n <= 1)
return false;
if (n == 2)
return true;
for (int i = 2; i <= Math.sqrt(n) + 1; i++) // Math.sqrt(n) returns the rounded square root of “n”
{
if (n % i == 0)
return false;
}
return true;
}
Explanation / Answer
Answer:
boolean x = prm(25); will return false. so x value is false
Math.sqrt(25) will give 5. so when i value is 5 if condition will return false.
boolean y = prm(17); will return true. so x value is true
Math.sqrt(17) will give 4.1 value. so if condition will always false for all condition. so it will return true.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.