Day 16:-
Problem Statement:-Time Complexity: Primality
Simple problem,If its even no then its definately not prime,if its odd no,then loop n/2 times and try to find the divisor if not found any then its prime.
Solution:-
Problem Statement:-Time Complexity: Primality
Simple problem,If its even no then its definately not prime,if its odd no,then loop n/2 times and try to find the divisor if not found any then its prime.
Solution:-
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int p = in.nextInt(); for (int a0 = 0; a0 < p; a0++) { int n = in.nextInt(); System.out.println(isPrime(n)); } } private static String isPrime(int n) { if (n==1){ return "Not prime"; } if (n==2) return "Prime"; if (n % 2 == 0) { return "Not prime"; } for (int i = 3; i <= Math.sqrt(n); i++) { if (n % i == 0) { return "Not prime"; } } return "Prime"; } }
No comments:
Post a Comment