Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should a boolean isPrime() return for negative numbers?

Tags:

primes

I have a function that tests if this number is a prime.

public static boolean isPrime(int number) {

    if (number == 2) {
        return true;
    } else if (number > 2) {
        //faster method: number is even ? false : test odd divisors
        for (int counter = 2; counter * counter >= number; counter++) {
            if (number % counter == 0) {
                return false;
            }
        }
        return true;
    } else {
        return false; //what should it return 1, 0, negative numbers?   
    }
}

What should it return if a number is less than 2? This is an exam question and test sets will be non-negative integers. Code quality is evaluated as well, so what is the common way to deal with negative numbers? Throw exception? declare all negative numbers prime/composite?

like image 425
UIUXU Avatar asked Dec 31 '25 10:12

UIUXU


2 Answers

A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. A composite number is a positive integer which is not prime (i.e., which has factors other than 1 and itself).

Note that

isPrime(1); //false
isComposite(1); //false

return false; //what should it return 1, 0, negative numbers? This is correct all numbers below 2 are not primes. And not composite as well.

like image 59
Stepan Avatar answered Jan 06 '26 16:01

Stepan


Some possibilities for negative inputs:

  • Return composite. Examples: Wolfram/Alpha, Pari/GP, Perl/ntheory, mpz_prp used by Python/gmpy2.

  • Indicate a domain error. It isn't a wrong solution.

  • Return isprime(-n). We just use abs(n) as the input. PFGW does this, though also prints a message about it. I think this is a dubious choice for most purposes (PFGW is a somewhat special case).

  • Return incorrect results. Don't do this. Sometimes seen when someone casts any input into an unsigned integer type without any checks.

There are other inputs to consider, such as what one does with floating point inputs, complex, NaN, inf, strings, 64-bit unsigned, > 64-bit, etc. How much of this you control depends on the language and how willing it is to silently cast arguments.

Also, as Stepan notes, 1 is neither prime nor composite.

like image 29
DanaJ Avatar answered Jan 06 '26 17:01

DanaJ



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!