Last active
July 29, 2018 10:07
-
-
Save lzzy12/abf7e19a934e3a3f83cd603a0b56eb81 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import static java.lang.Math.sqrt; | |
public class HelloWorld { | |
public static boolean isSqrNum(int input) | |
{ | |
// If the sqrt(input) is an integer, then it is a perfect square or square number | |
return (sqrt(input) % 1 == 0); | |
} | |
public static boolean isTriangle(int input) | |
{ | |
/*This method is probably the most fastest way to check if a number is Triangular or not (At least I can't think of any faster algorithm) | |
It basically uses the "S = n(n + 1) / 2" formula which gives the summation of first n natural numbers. By this way we don't have to use a | |
damn slow for loop or while loop which checks each natural number to be the summation of the input. | |
From the formula, S = n(n + 1) / 2, we get 2*S = n^2 + n or n^2 + n - 2*S = 0; or n = (-1 + sqrt(1 + 8 * S) )/ 2; [By dhanacharya's formula of quadratic equation] | |
*/ | |
return (input > 0 && ((sqrt(1 + 8 * input) - 1) / 2) % 1 == 0); | |
} | |
public static void main(String[] args) { | |
float TriangularNum = 0; | |
for (float i = 0; i < 100; i++) | |
{ | |
TriangularNum += i * 0.1; | |
System.out.println(isTriangle(TriangularNum)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment