Prime numbers#830

Prime numbers (Editorial)

Iterate through all positive integers in the range from to and print only the prime numbers. If there are no prime numbers in the range , print the message "Absent".

Algorithm implementation

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 data.

scanf("%d %d",&m,&n);

Initially, assume that there are no prime numbers in the range. Set flag = 0.

flag = 0;

Iterate through the numbers from to . If the current number is prime, print it and set flag = 1.

for(i = m; i <= n; i++)
{
  if (IsPrime(i))
  {
    printf("%d\n",i);          
    flag = 1;
  }
}

If no prime number is printed (flag = 0), print the message "Absent".

if (flag == 0) puts("Absent");

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 data.

m, n = map(int,input().split())

Initially, assume that there are no prime numbers in the range. Set flag = 0.

flag = 0

Iterate through the numbers from to . If the current number is prime, print it and set flag = 1.

for i in range(m, n + 1):
  if IsPrime(i):
    print(i)
    flag = 1

If no prime number is printed (flag = 0), print the message "Absent".

if flag == 0: print("Absent")