Monday, December 19, 2022

Java Program to Display Prime Numbers

This post shows a Java program to display prime numbers.

As we know that a number is a prime number if it is a natural number greater than 1 and it can be divided either by 1 or by the number itself. As example- 2, 3, 5, 7, 11, 13, 17 ….

To check if a number is prime or not you need to run a loop starting from 2 till number/2 to check if number has any divisor.

For example, if number is 8 then you just need to check till 4 (8/2) to see if it divides by any number or not. Same way if you have a number 15 you just need to check till 7 to see if it divides completely by any number or not. We'll use the same logic to write our program to display prime numbers up to the given upper range.

Java program to print prime numbers

import java.util.Scanner;

public class PrintPrime {
  public static void main(String[] args) {
    // take input from the user
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number till which prime numbers are to be printed: ");
    int num = sc.nextInt();
    for(int i = 2; i <= num; i++){
      if(isPrime(i)){
        System.out.print(i + " ");
      }
    }
  }
  // Method to check if the passed number
  // is prime or not    
  private static boolean isPrime(int num){
    boolean flag = true;
    // loop from 2, increment it till number/2
    for(int i = 2; i <= num/2; i++){
      // no remainder, means divides 
      if(num % i == 0){
        flag = false;
        break;
      }
    }
    return flag;
  }
}

Output

Enter number till which prime numbers are to be printed: 
50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Here scanner class is used to get input from the user.

That's all for this topic Java Program to Display Prime Numbers. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Check Prime Number
  2. Armstrong Number or Not Java Program
  3. How to Display Pyramid Patterns in Java - Part2
  4. Java Program to Reverse a Number
  5. Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program

You may also like-

  1. Find Duplicate Elements in an Array Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Check if Given String or Number is a Palindrome Java Program
  4. Polymorphism in Java
  5. Difference Between Abstract Class And Interface in Java
  6. Java Automatic Numeric Type Promotion
  7. Java Pass by Value or Pass by Reference
  8. finally Block in Java Exception Handling

No comments:

Post a Comment