How to Check Pronic Number in Java

A pronic number is a product of two consecutive integers. Pronic numbers can be expressed in the form n(n+1). For example, 6 is a pronic number since it is the product of two consecutive integers 2 and 3.  These numbers are also known as oblong numbers or heteromecic numbers. Following are the first 10 pronic numbers,

0, 2, 6, 12, 20, 30, 42, 56, 72, 90.

Pronic numbers have some interesting properties. All pronic numbers are even integers and the n-th pronic number is the some of the first n even integers.

Problem: Write a java program to check whether a given number is a pronic number

We know that a pronic number is of the form n(n+1). Hence if we find the square root of a pronic number and then round it to the lower integer, we will get n. If we multiply it with the next integer and if the result is same as the original number we know that the given number is a pronic number! The following Java program uses the above logic to check whether a given number is pronic or not.

import java.util.Scanner;

// Java pronic number checker example
public class PronicNumberChecker {

    // Check whether a given number is pronic or not
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Please enter a number: ");
        long number = s.nextLong();
        
        long n = (long)Math.sqrt(number);
        if(n*(n+1)==number) {
            System.out.println(number+" is a pronic number");
        }else {
            System.out.println(number+" is NOT a pronic number");
        }
        s.close();
    }
}

Here is a sample output of the program,

Please enter a number: 30
30 is a pronic number

Problem: Write a java program to generate first n pronic numbers

Generating first n pronic numbers is trivial. We iterate from 0 till n-1 and compute the product of the current number with the next number. The following Java program generates the first n pronic numbers.

import java.util.Scanner;

// Java example program to generate pronic number sequence
public class PronicNumberGenerator {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("How many pronic numbers you need? ");
        long n = s.nextLong();
        
        // Print first n pronic numbers
        for(long i =0;i<n;i++) {
            System.out.print(i*(i+1));
            if(i!=n-1) {
                System.out.print(",");
            }
        }
        
        s.close();
    }
}

Here is the sample output of the program,

How many pronic numbers you need? 10
0,2,6,12,20,30,42,56,72,90