The problem
Outline a perform that takes one integer argument and returns a logical worth true or false relying on if the integer is a chief.
Per Wikipedia, a chief quantity (or a chief) is a pure quantity higher than 1 that has no optimistic divisors aside from 1 and itself.
Necessities:
- You’ll be able to assume you’ll be given an integer enter.
- You cannot assume that the integer will probably be solely optimistic. Chances are you’ll be given adverse numbers as nicely (or “).
- NOTE on efficiency: There aren’t any fancy optimizations required, however nonetheless the most trivial options may day out. Numbers go as much as 2^31 (or comparable, is determined by language model). Looping all the best way as much as
n, orn/2, will probably be too sluggish.
Instances:
is_prime(1) /* false */
is_prime(2) /* true */
is_prime(-1) /* false */
The answer in Java code
Possibility 1:
public class Prime {
public static boolean isPrime(int num) {
return num > 1 && java.math.BigInteger.valueOf(num).isProbablePrime(20);
}
}
Possibility 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;
}
}
Possibility 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;
}
}
Take a look at instances to validate our resolution
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Take a look at;
public class PrimeTest {
@Take a look at
public void testBasic() {
assertFalse("0 shouldn't be prime", Prime.isPrime(0));
assertFalse("1 shouldn't be prime", Prime.isPrime(1));
assertTrue ("2 is prime", Prime.isPrime(2));
assertTrue ("73 is prime", Prime.isPrime(73));
assertFalse("75 shouldn't be prime", Prime.isPrime(75));
assertFalse("-1 shouldn't be prime", Prime.isPrime(-1));
}
@Take a look at
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));
}
@Take a look at
public void testNotPrime() {
assertFalse("4 shouldn't be prime", Prime.isPrime(4));
assertFalse("6 shouldn't be prime", Prime.isPrime(6));
assertFalse("8 shouldn't be prime", Prime.isPrime(8));
assertFalse("9 shouldn't be prime", Prime.isPrime(9));
assertFalse("45 shouldn't be prime", Prime.isPrime(45));
assertFalse("-5 shouldn't be prime", Prime.isPrime(-5));
assertFalse("-8 shouldn't be prime", Prime.isPrime(-8));
assertFalse("-41 shouldn't be prime", Prime.isPrime(-41));
}
}