Editorial
Algorithm Analysis
A number is called prime if it has no other divisors except for one and itself.
Theorem. If a number is composite, then it must have a divisor not greater than .
Proof. Suppose is composite and is its divisor. Then will also be a divisor of . If we assume that all divisors of are greater than , then and . From here or , which is a contradiction.
To check if a number is prime, it is enough to check if it is divisible by any number from 2 to inclusive. If is divisible by at least one of them, then is composite. Otherwise, it is prime.
Algorithm Implementation
Read the value of . Initially set flag
= 1, this means that is prime.
scanf("%d", &n); flag = 1;
Iterate over all possible divisors of the number . If is divisible by , then it is composite, set flag
= 0.
for(i = 2; i <= sqrt(n); i++) if (n % i == 0) { flag = 0; break; }
Depending on the value of flag
, output the answer.
if (flag == 0) printf("No\n"); else printf("Yes\n");
Implementation of the Algorithm – Through a Prime Checking Function
#include <stdio.h> #include <math.h> int n; int IsPrime(int n) { for(int i = 2; i <= sqrt(n); i++) if (n % i == 0) return 0; return 1; } int main(void) { scanf("%d", &n); if (IsPrime(n)) printf("Yes\n"); else printf("No\n"); return 0; }
Java Implementation
import java.util.*; public class Main { static boolean IsPrime(int n) { for(int i = 2; i <= Math.sqrt(n); i++) if (n % i == 0) return false; return true; } public static void main(String[] args) { Scanner con = new Scanner(System.in); int n = con.nextInt(); if (IsPrime(n)) System.out.println("Yes"); else System.out.println("No"); con.close(); } }
Python Implementation
import math def IsPrime(n): for i in range(2, int(math.sqrt(n))+1): if n % i == 0: return False return True n = int(input()) if IsPrime(n): print("Yes") else: print("No")