|
| 1 | +package com.sbiswas001.twelveproject; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +/** |
| 6 | + * This class checks if a number is triangular or not. |
| 7 | + * A number is triangular if it is formed by the addition |
| 8 | + * of consecutive sequence of integers starting from 1. |
| 9 | + * @author Sayan Biswas |
| 10 | + * @version 23.04.2022 |
| 11 | + */ |
| 12 | +public class TriangularNumber { |
| 13 | + |
| 14 | + /** |
| 15 | + * Stores the number |
| 16 | + */ |
| 17 | + private int x; |
| 18 | + |
| 19 | + /** |
| 20 | + * Initializes instance variables |
| 21 | + */ |
| 22 | + private TriangularNumber() { |
| 23 | + x=0; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * Inputs number from user |
| 28 | + */ |
| 29 | + private void input() { |
| 30 | + Scanner sc = new Scanner(System.in); |
| 31 | + System.out.print("Enter natural number: "); |
| 32 | + x = Integer.parseInt(sc.next()); |
| 33 | + if(x < 1) { |
| 34 | + System.out.println("Wrong input! Try again."); |
| 35 | + input(); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * This method checks if a number is triangular or not. |
| 41 | + * A number is triangular if it is formed by the addition |
| 42 | + * of consecutive sequence of integers starting from 1. |
| 43 | + * Let x be the sum of n consecutive numbers from 1. |
| 44 | + * So, x=n*(n+1)/2, where n is a natural number. |
| 45 | + * Calculating we get, n=-0.5+-(Math.sqrt(1+8*x))/2 |
| 46 | + * If n is a natural number then x is a triangular number. |
| 47 | + * @return true or false |
| 48 | + */ |
| 49 | + private boolean triangularCheck() { |
| 50 | + double n1, n2; |
| 51 | + n1 = -0.5+(Math.sqrt(1+8*x))/2; |
| 52 | + n2 = -0.5-(Math.sqrt(1+8*x))/2; |
| 53 | + return n1 % 1 == 0 || n2 % 1 == 0; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Calls other methods |
| 58 | + * @param args Arguments passed to main method |
| 59 | + */ |
| 60 | + public static void main(String[] args) { |
| 61 | + TriangularNumber ob = new TriangularNumber(); |
| 62 | + ob.input(); |
| 63 | + System.out.println(ob.triangularCheck() ? |
| 64 | + "Number is a triangular number." : |
| 65 | + "Number is not a triangular number."); |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments