Problem: Write a Java program to check whether the given number is a Pronic number or not.

A pronic number is a number that can be represented as a product of two consecutive numbers.

Some examples of pronic numbers are: 6, 12, 20, etc.

Pronic numbers

A pronic number is also known as a Rectangular or Oblong number.

To check whether a number is pronic in java, we find the square root of the number or the number close to the square root (because the product of any two consecutive numbers is always closest to the square of one of them).

Then we check if its product with the next number (n+1) is equal to the original number. If so, the number is pronic otherwise not.

import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
  
    System.out.println("Enter a number");
    int num = in.nextInt();
 
    //Find sqaure root or nearest to sqaure root
    int sqrtNum = (int)Math.sqrt(num);
 
    //check if the product of two consecutive number 
    //is equal with the original number
    if(num == (sqrtNum*(sqrtNum+1))){
      System.out.println("Pronic number");
    } else {
      System.out.println("Not a Pronic number");
    }
  }
}

Output:

Enter a number
12
Pronic number

Print all Pronic Numbers in Given Interval

To print all pronic numbers in the given interval, we write the logic of checking the protonic number in a separate function and call the same for each number in the given interval.

import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    boolean flag = false;
  
    System.out.print("Enter a lower and upper range value: ");
    int low = in.nextInt();
    int upper = in.nextInt();
 
    //Loop through each value in the given range
    for(int i=low; i<=upper; i++){
      if(isPronic(i)){
        flag = true;
        System.out.print(i+" ");
      }
    }
 
    //If 'flag' remains false then there was no pronic number in the range
    if(flag == false)
      System.out.println("No Pronic numbers within given range");
  }
 
  //Function to check pronic number
  private static boolean isPronic(int num){
    //Find sqaure root or nearest to sqaure root
    int sqrtNum = (int)Math.sqrt(num);
 
    //return the test of eqaulity of product of two 
    //consecutive number with the original number
    return (num == (sqrtNum*(sqrtNum+1)));
    
  }
}

Output:

Enter a lower and upper range value: 1 100
2 6 12 20 30 42 56 72 90

In this programming example, we learned to check pronic number using the Java language.

Leave a Reply