Prime number?#1616

Prime number? (Editorial)

A number is called prime if it has no divisors other than and itself.

Тheorem. If a number is composite, then it must have a divisor that does not exceed \sqrt{n}.

Proof. Let be a composite number, and let be one of its divisors. Then is also a divisor of . Assume that all divisors of are greater than \sqrt{n}. Then the inequalities d > \sqrt{n} и n / d > \sqrt{n} hold simultaneously. Multiplying these inequalities, we get:

d * (n / d) > \sqrt{n} * \sqrt{n},

which simplifies to n > n. This is a contradiction. Therefore, if is composite, at least one of its divisors does not exceed \sqrt{n}.

To check whether a number is prime, it is sufficient to verify if it is divisible by any number from to \sqrt{n} inclusive. If is divisible by at least one of these numbers, then is composite. Otherwise, is prime.

Algorithm implementation

Read the input value of .

scanf("%d",&n);

Set the flag flag = 1. This means that is initially assumed to be a prime number.

flag = 1;

Iterate through all possible divisors of the number from to \sqrt{n} inclusive. If is divisible by , then is composite, so set flag = 0.

for (i = 2; i <= sqrt(n); i++)
  if (n % i == 0)
  {
    flag = 0;
    break;
  }

Based on the value of , print the result.

if (flag == 0) printf("No\n"); 
else printf("Yes\n");

Algorithm implementation — function

The function IsPrime checks whether the number is prime.

int IsPrime(int n)
{
  for (int i = 2; i <= sqrt(n); i++)
    if (n % i == 0) return 0;
  return 1;
}

The main part of the program. Read the input value of .

scanf("%d",&n);

Based on the primality of the number , print the result.

if (IsPrime(n)) printf("Yes\n"); 
else printf("No\n");

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

The function IsPrime checks whether the number is prime.

def IsPrime(n):
  for i in range(2, int(math.sqrt(n))+1):
    if n % i == 0: return False
  return True

The main part of the program. Read the input value of .

n = int(input())

Based on the primality of the number , print the result.

if IsPrime(n):
  print("Yes")
else:
  print("No")