A prime is a natural number greater than that has no positive divisors other than and itself. Given integers, determine the primality of each integer and print whether it is Prime
or Not prime
on a new line.
Note: If possible, try to come up with an primality algorithm, or see what sort of optimizations you can come up with for an algorithm. Be sure to check out the Editorial after submitting your code!
Time Complexity: Primality - Hacker Rank Solution
Python 3
import math def isPrime(n): if n == 2: return True elif n == 1 or (n & 1) == 0: return False for i in range(2, math.ceil(math.sqrt(n)) + 1): if (n % i) == 0: return False return True p = int(input()) for i in range(0, p): x = int(input()) s = "Prime" if (isPrime(x)) else "Not prime" print(s);
Java
import java.util.*;
public class Solution {
/**
* Improved O( n^(1/2)) ) Algorithm
* Checks if n is divisible by 2 or any odd number from 3 to sqrt(n).
* The only way to improve on this is to check if n is divisible by KNOWN PRIMES from 2 to sqrt(n).
*
* @param n An integer to be checked for primality.
* @return true if n is prime, false if n is not prime.
**/
public static boolean isPrime(int n){
// check lower boundaries on primality
if( n == 2 ){
return true;
} // 1 is not prime, even numbers > 2 are not prime
else if( n == 1 || (n & 1) == 0){
return false;
}
// Check for primality using odd numbers from 3 to sqrt(n)
for(int i = 3; i <= Math.sqrt(n); i += 2){
// n is not prime if it is evenly divisible by some 'i' in this range
if( n % i == 0 ){
return false;
}
}
// n is prime
return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
for(int i = 0; i < testCases; i++){
System.out.println(
(isPrime(scan.nextInt()) ? "Prime" : "Not prime") );
}
scan.close();
}
}
No comments:
Post a Comment