Friday, September 22, 2023
HomeSoftware EngineeringIs a Quantity Prime in Java

# Is a Quantity Prime in Java

## The problem#

Outline a operate that takes one integer argument and returns a logical worth `true` or `false` relying on if the integer is a major.

Per Wikipedia, a major quantity (or a major) is a pure quantity larger than 1 that has no constructive divisors apart from 1 and itself.

Necessities:

• You may assume you’ll be given an integer enter.
• You cannot assume that the integer will probably be solely constructive. Chances are you’ll be given unfavourable numbers as properly (or “).
• NOTE on efficiency: There aren’t any fancy optimizations required, however nonetheless the most trivial options may trip. Numbers go as much as 2^31 (or comparable, is determined by language model). Looping all the best way as much as `n`, or `n/2`, will probably be too gradual.

Instances:

``````is_prime(1)  /* false */
is_prime(2)  /* true  */
is_prime(-1) /* false */
``````

## The answer in Java code#

Choice 1:

``````public class Prime {
public static boolean isPrime(int num) {
return num > 1 && java.math.BigInteger.valueOf(num).isProbablePrime(20);
}
}
``````

Choice 2:

``````public class Prime {
public static boolean isPrime(int quantity) {
if(quantity < 2)
return false;
for (int i=2; i<=Math.sqrt(quantity); i++){
if(quantity % i == 0)
return false;
}
return true;
}
}
``````

Choice 3:

``````public class Prime {
public static boolean isPrime(int num) {
if (num == 2) return true;
if (num < 2 || num % 2 == 0) return false;
for (int i = 3; num >= i*i; i+=2) {
if (num % i == 0) return false;
}
return true;
}
}
``````

## Check circumstances to validate our answer#

``````import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Check;

public class PrimeTest {
@Check
public void testBasic() {
assertFalse("0  just isn't prime", Prime.isPrime(0));
assertFalse("1  just isn't prime", Prime.isPrime(1));
assertTrue ("2  is prime",     Prime.isPrime(2));
assertTrue ("73 is prime",     Prime.isPrime(73));
assertFalse("75 just isn't prime", Prime.isPrime(75));
assertFalse("-1 just isn't prime", Prime.isPrime(-1));
}
@Check
public void testPrime() {
assertTrue("3 is prime", Prime.isPrime(3));
assertTrue("5 is prime", Prime.isPrime(5));
assertTrue("7 is prime", Prime.isPrime(7));
assertTrue("41 is prime", Prime.isPrime(41));
assertTrue("5099 is prime", Prime.isPrime(5099));
}
@Check
public void testNotPrime() {
assertFalse("4 just isn't prime", Prime.isPrime(4));
assertFalse("6 just isn't prime", Prime.isPrime(6));
assertFalse("8 just isn't prime", Prime.isPrime(8));
assertFalse("9 just isn't prime", Prime.isPrime(9));
assertFalse("45 just isn't prime", Prime.isPrime(45));
assertFalse("-5 just isn't prime", Prime.isPrime(-5));
assertFalse("-8 just isn't prime", Prime.isPrime(-8));
assertFalse("-41 just isn't prime", Prime.isPrime(-41));
}
}
``````
RELATED ARTICLES