Write a program to input a number and check and print whether it is a Pronic number or not. A Pronic number is a number which is the product of two consecutive integers. Examples: 12 = 3 x 4 20 = 4 x 5 42 = 6 x 7
Topic: Checking for a Pronic number
Answer
import java.util.Scanner;
class Pronic { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number : "); int n = sc.nextInt();
boolean found = false;
for(int i = 1; i * (i + 1) <= n; i++) { if(i * (i + 1) == n) { found = true; System.out.println(n + " = " + i + " x " + (i + 1)); break; } }
if(found) System.out.println(n + " is a Pronic number"); else System.out.println(n + " is not a Pronic number"); } }
The definition translates directly into code: test whether n equals i * (i + 1) for some whole number i.
The clever part is the loop condition. Rather than looping to n, stop as soon as i * (i + 1) exceeds n — beyond that point no larger i could possibly work. For n = 42 the loop runs only six times instead of forty-two.
A boolean flag records the result, and break leaves the loop the moment a match is found. Flag-and-break is the standard shape for "does such a thing exist" questions, and it is worth recognising as a pattern.
Printing the factor pair (12 = 3 x 4) is not demanded but shows the working, which examiners reward.
Trace 12: i = 1 gives 2, i = 2 gives 6, i = 3 gives 12 — a match, so 12 is Pronic. Trace 15: the products go 2, 6, 12, 20 and 20 exceeds 15, so the loop ends with no match.
n int - the number entered by the user i int - loop variable, the smaller of the two consecutive integers found boolean - flag recording whether a matching pair was found sc Scanner - object used to read input