Confusion over java return at end of method

I do not understand the meaning of "return" at the end of the isPrime method, it is true.

public class PrimeNumber extends ConsoleProgram{ public void run(){ int number = readInt("Enter number: "); if(isPrime(number)){ println( number + " is prime number"); }else{ println(number + " is not a prime number"); }; } private boolean isPrime(int n){ for(int i=2;i<n;i++){ if (n % i == 0) { return false; } } return true; } 

It returns false when it finds a divider, but I don’t understand why, outside the loop, it returns true?

+4
source share
4 answers

The isPrime function assumes the number is prime. The cycle is looking for a counter example that will refute this assumption. If no counter example is found, the loop reaches its end and the function returns true .

This is known in logic as proof of contradiction . In cases where most of your results will be false (for example, since most of the numbers are not first), this is considered good programming practice because it leads to errors and returns algorithms as quickly as possible, leading to better performance.

+1
source

It returns true by default. Therefore, if he completes the cycle, having passed all the numbers that check the divisibility, and finds that none divides him, he returns true. It is written in such a way that your method will return false if it finds any number dividing your parameter, and return true only if it checks all the numbers that it wants to check and does not find a single division of the parameter with a residual zero.

A method declared using a boolean type MUST return something always, a method cannot just end without returning anything.

Note. You do not need to check every number last than X for divisibilty to see if x is prime. You only need to check and include the square root of X, see. This is for reference: Why do we check the square root of a prime number to determine if it is prime?

+1
source

In principle, this allows the programmer to take some freedom in simplifying the code in this case.

If inside the loop, (n % i == 0) is true, the if statement is executed. false returns and the method stops.

Alternatively, if this expression is never true, the loop ends and true is returned.

Placing a return at the end of a code fragment that may return something conditionally helps with clearing the initial condition and avoids warnings or compiler errors.

0
source

he is right, but if you want to check if the number is prime, you only need to check n / 2!

0
source

Source: https://habr.com/ru/post/1490978/


All Articles