In this example, I have shared a Java program to print all the prime numbers between given range. This program takes two input numbers a and b as interval range, and finds find all the prime numbers in between the interval.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | /** * Program to print all the prime numbers between given range. * @author: Nilendra Kumar. * */ package com.common.program; import java.util.Scanner; public class PrimeNumbers { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the lower limit: "); int a = sc.nextInt(); System.out.print("Enter the upper limit: "); int b = sc.nextInt(); System.out.println("Prime numbers between "+a+" and "+b+ " are: "); int counter = 0; while(a <= b) { boolean prime = true; for(int i = 2; i <= a/2; i++) { if(a % i == 0) { prime = false; break; } } if(prime && a != 1) { System.out.print(a+" "); counter++; if(counter % 20 == 0) { System.out.println(); } } a++; } } } |
Program output
1 2 3 4 | Enter the lower limit: 20 Enter the upper limit: 50 Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47 |
This program is contributed by Nilendra Kumar. Here is same the program using C programming language.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.