Hello coders, today we are going to solve Prime Generator CodeChef Solution whose Problem Code is PRIME1.
Task
Ram wants to generate some prime numbers for his cryptosystem. Help him please! Your task is to generate all prime numbers between two given numbers.
Input Format
The first line contains t, the number of test cases (less then or equal to 10). Followed by t lines which contain two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output Format
For every test case print all prime numbers p such that m <= p <= n, one number per line. Separate the answers for each test case by an empty line.
Example
Sample Input
2
1 10
3 5
Sample Output
2
3
5
7
3
5
Solution – Prime Generator
C++
#include <bits/stdc++.h> using namespace std; bool prime(int n){ for(int i=2 ; i<=sqrt(n) ; i++) { if(n%i==0) return false; } return true; } int main() { int t; cin >> t; while (t--) { int m ,n ; cin >> m >>n ; if (m==1) m++; for (int i = m ; i <=n ; i++){ if (prime(i)) cout << i << endl; } cout <<"\n"; } return 0; }
Python
# cook your dish here import math def ret(i): if i==1: return 0 if i==2 or i==3: return 1 if i%2==0 or i%3==0: return 0 n=math.floor(math.sqrt(i)) for j in range(5,n+1,6): if i%j==0 or i%(j+2)==0: return 0 return 1 t=int(input()) for i in range(t): m,n=map(int,input().split()) for i in range(m,n+1): k=ret(i) if k!=0: print(i,end=" ")
Java
import java.util.Scanner; public class Main{ public static int findprime(int n){ if (n == 1) { return 0; } for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) { return 0; } } return 1; } public static void main(String[] args) { int t,m,n; Scanner in=new Scanner(System.in); t=in.nextInt(); while(t!=0){ m=in.nextInt(); n=in.nextInt(); int i; for (i=m;i<=n ;i++ ) { if (findprime(i)==1) { System.out.println(i); } } t--; } } }
Disclaimer: The above Problem (Prime Generator) is generated by CodeChef but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.