7 Commits

Author SHA1 Message Date
2d76848a69 Update dependencies and plugins 2025-01-11 11:59:01 -05:00
7e66910d8c Update with nvd api key 2024-08-16 23:31:19 -04:00
00658869d2 Update snapshot version 2024-08-11 21:41:17 -04:00
efdc72a71e Fix version number 2024-08-11 21:38:06 -04:00
dbac819ac9 Fix broken javadoc comments 2024-08-11 21:37:35 -04:00
3feefdb7dd Added javadoc comments 2024-08-11 21:31:00 -04:00
ae1346dbcd Update snapshot version 2024-08-08 22:10:15 -04:00
12 changed files with 839 additions and 73 deletions

38
pom.xml
View File

@@ -20,19 +20,20 @@
</developers>
<scm>
<connection>scm:git:git://bitbucket.org/Mattrixwv/Matrix.git</connection>
<developerConnection>scm:git:ssh://bitbucket.org:Mattrixwv/Matrix.git</developerConnection>
<url>https://bitbucket.org/Mattrixwv/Matrix/src</url>
<connection>scm:git:git://bitbucket.org/Mattrixwv/JavaClasses.git</connection>
<developerConnection>scm:git:ssh://bitbucket.org:Mattrixwv/JavaClasses.git</developerConnection>
<url>https://bitbucket.org/Mattrixwv/JavaClasses/src</url>
</scm>
<groupId>com.mattrixwv</groupId>
<artifactId>myClasses</artifactId>
<version>1.3.5</version>
<version>1.3.7</version>
<name>myClasses</name>
<description>A grouping of functions that I've found useful</description>
<url>www.mattrixwv.com</url>
<properties>
<!--Compile-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@@ -50,11 +51,12 @@
<gpg.keyname>3BA6515C8FF145249BEBBEABA52FDEC4259179D4</gpg.keyname>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.3</version>
<version>5.11.4</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -104,7 +106,7 @@
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.3.1</version>
<version>3.5.2</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
@@ -112,24 +114,24 @@
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version>
<version>3.1.3</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.2</version>
<version>3.1.3</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.12.1</version>
<version>3.21.0</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.6.2</version>
<version>3.8.0</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.17.1</version>
<version>2.18.0</version>
<configuration>
<rulesUri>file://${session.executionRootDirectory}/version-rules.xml</rulesUri>
</configuration>
@@ -137,14 +139,14 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.7.1</version>
<version>3.8.1</version>
</plugin>
<!--Sonarqube-->
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>4.0.0.4121</version>
<version>5.0.0.4389</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
@@ -170,7 +172,7 @@
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>10.0.3</version>
<version>12.0.0</version>
<executions>
<execution>
<phase>none</phase>
@@ -184,6 +186,7 @@
<format>json</format>
<format>html</format>
</formats>
<nvdApiServerId>nvd</nvdApiServerId>
</configuration>
</plugin>
@@ -191,7 +194,7 @@
<plugin>
<groupId>org.sonatype.central</groupId>
<artifactId>central-publishing-maven-plugin</artifactId>
<version>0.5.0</version>
<version>0.7.0</version>
<extensions>true</extensions>
<configuration>
<publishingServerId>ossrh</publishingServerId>
@@ -227,7 +230,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.8.0</version>
<version>3.11.2</version>
<executions>
<execution>
<id>attach-javadocs</id>
@@ -241,7 +244,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.2.4</version>
<version>3.2.7</version>
<executions>
<execution>
<id>sign-artifacts</id>
@@ -251,7 +254,6 @@
</goals>
<configuration>
<keyname>${gpg.keyname}</keyname>
<passphraseServerId>${gpg.keyname}</passphraseServerId>
</configuration>
</execution>
</executions>

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/ArrayAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 06-25-22
//Modified: 08-11-24
//This class contains algorithms for vectors that I've found it useful to keep around
/*
Copyright (C) 2022 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -28,9 +28,26 @@ import java.util.List;
import java.util.StringJoiner;
/**
* The {@code ArrayAlgorithms} class provides static utility methods for performing
* arithmetic operations on collections of numbers, including integers, longs, and BigIntegers.
* It also includes utility methods for printing and converting lists.
*
* <p>This class is not intended to be instantiated.</p>
*/
public class ArrayAlgorithms{
/**
* Private constructor to prevent instantiation of this utility class.
*/
private ArrayAlgorithms(){}
//This function returns the sum of all elements in the list
//?This function returns the sum of all elements in the list
/**
* Returns the sum of all elements in the given iterable collection of integers.
*
* @param nums the iterable collection of integers to sum
* @return the sum of all integers in the collection
*/
public static int getSum(Iterable<Integer> nums){
//Setup the variables
int sum = 0;
@@ -43,6 +60,12 @@ public class ArrayAlgorithms{
//Return the sum of all elements
return sum;
}
/**
* Returns the sum of all elements in the given iterable of longs.
*
* @param nums the iterable collection of longs to sum
* @return the sum of all longs in the collection
*/
public static long getLongSum(Iterable<Long> nums){
//Setup the variables
long sum = 0;
@@ -55,6 +78,12 @@ public class ArrayAlgorithms{
//Return the sum of all elements
return sum;
}
/**
* Returns the sum of all elements in the given iterable collection of {@code BigInteger} objects.
*
* @param nums the iterable collection of {@code BigInteger} objects to sum
* @return the sum of all {@code BigInteger} objects in the collection
*/
public static BigInteger getBigSum(Iterable<BigInteger> nums){
//Setup the variables
BigInteger sum = BigInteger.ZERO;
@@ -67,7 +96,15 @@ public class ArrayAlgorithms{
//Return the sum of all elements
return sum;
}
//This function returns the product of all elements in the list
//?This function returns the product of all elements in the list
/**
* Returns the product of all elements in the given iterable collection of integers.
* If the iterable is empty, it returns 0.
*
* @param nums the iterable collection of integers to multiply
* @return the product of all integers in the collection, or 0 if the collection is empty
*/
public static int getProd(Iterable<Integer> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){
@@ -85,6 +122,13 @@ public class ArrayAlgorithms{
//Return the product of all elements
return product;
}
/**
* Returns the product of all elements in the given iterable collection of longs.
* If the iterable is empty, it returns 0.
*
* @param nums the iterable collection of longs to multiply
* @return the product of all longs in the collection, or 0 if the collection is empty
*/
public static long getLongProd(Iterable<Long> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){
@@ -102,6 +146,13 @@ public class ArrayAlgorithms{
//Return the product of all elements
return product;
}
/**
* Returns the product of all elements in the given iterable collection of {@code BigInteger} objects.
* If the collection is empty, it returns 0.
*
* @param nums the iterable collection of {@code BigInteger} objects to multiply
* @return the product of all {@code BigInteger} objects in the collection, or 0 if the collection is empty
*/
public static BigInteger getBigProd(Iterable<BigInteger> nums){
//If a blank list was passed tot he fuction return 0 as the product
if(!nums.iterator().hasNext()){
@@ -119,7 +170,16 @@ public class ArrayAlgorithms{
//Return the product of all elements
return product;
}
//Print a list
//?Print a list
/**
* Returns a string representation of the given iterable collection, with elements separated by commas
* and enclosed in square brackets.
*
* @param list the iterable collection to print
* @param <T> the type of elements in the collection
* @return a string representation of the collection
*/
public static <T> String printList(Iterable<T> list){
StringJoiner returnString = new StringJoiner(", ", "[", "]");
for(T obj : list){
@@ -127,7 +187,14 @@ public class ArrayAlgorithms{
}
return returnString.toString();
}
//Convert lists
//?Convert lists
/**
* Converts a list of {@code Long} objects to a list of {@code Integer} objects.
*
* @param originalList the list of {@code Long} objects to convert
* @return a list of {@code Integer} objects
*/
public static List<Integer> longToInt(List<Long> originalList){
ArrayList<Integer> newList = new ArrayList<>(originalList.size());
for(Long num : originalList){

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/NumberAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 04-13-23
//Modified: 08-11-24
//This class contains algorithms for numbers that I've found it useful to keep around
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -32,15 +32,40 @@ import java.util.List;
import com.mattrixwv.exceptions.InvalidResult;
/**
* Utility class that provides a variety of number-related algorithms,
* such as prime number generation, Fibonacci number calculation,
* factorial computation, and greatest common divisor determination.
* <p> This class cannot be instantiated. </p>
*/
public class NumberAlgorithms{
/**
* Private constructor to prevent instantiation
*/
private NumberAlgorithms(){}
/**
* Error message used for invalid factorial inputs.
*/
public static final String FACTORIAL_NEGATIVE_MESSAGE = "n! cannot be negative";
//This function returns a list with all the prime numbers <= goalNumber
//?This function returns a list with all the prime numbers <= goalNumber
/**
* Returns a list of all prime numbers less than or equal to the specified number.
*
* @param goalNumber the upper limit for generating prime numbers
* @return a list of prime numbers less than or equal to {@code goalNumber}
* @see #getPrimes(long)
*/
public static List<Integer> getPrimes(int goalNumber){
return ArrayAlgorithms.longToInt(getPrimes((long) goalNumber));
}
/**
* Returns a list of all prime numbers less than or equal to the specified number.
*
* @param goalNumber the upper limit for generating prime numbers
* @return a list of prime numbers less than or equal to {@code goalNumber}
*/
public static List<Long> getPrimes(long goalNumber){
ArrayList<Long> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found
@@ -54,7 +79,7 @@ public class NumberAlgorithms{
primes.add(2L);
}
//We cna now start at 3 and skipp all even numbers, because they cannot be prime
//We can now start at 3 and skip all even numbers, because they cannot be prime
for(long possiblePrime = 3L;possiblePrime <= goalNumber;possiblePrime += 2L){
//Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
Double topPossibleFactor = Math.ceil(Math.sqrt(possiblePrime));
@@ -79,6 +104,12 @@ public class NumberAlgorithms{
Collections.sort(primes);
return primes;
}
/**
* Returns a list of all prime numbers less than or equal to the specified number.
*
* @param goalNumber the upper limit for generating prime numbers
* @return a list of prime numbers less than or equal to {@code goalNumber}
*/
public static List<BigInteger> getPrimes(BigInteger goalNumber){
ArrayList<BigInteger> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found
@@ -119,10 +150,23 @@ public class NumberAlgorithms{
}
//This function gets a certain number of primes
//?This function gets a certain number of primes
/**
* Returns a list of the specified number of prime numbers.
*
* @param numberOfPrimes the number of prime numbers to generate
* @return a list containing the first {@code numberOfPrimes} prime numbers
* @see #getNumPrimes(long)
*/
public static List<Integer> getNumPrimes(int numberOfPrimes){
return ArrayAlgorithms.longToInt(getNumPrimes((long)numberOfPrimes));
}
/**
* Returns a list of the specified number of prime numbers.
*
* @param numberOfPrimes the number of prime numbers to generate
* @return a list containing the first {@code numberOfPrimes} prime numbers
*/
public static List<Long> getNumPrimes(long numberOfPrimes){
ArrayList<Long> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found
@@ -161,6 +205,12 @@ public class NumberAlgorithms{
Collections.sort(primes);
return primes;
}
/**
* Returns a list of the specified number of prime numbers.
*
* @param numberOfPrimes the number of prime numbers to generate
* @return a list containing the first {@code numberOfPrimes} prime numbers
*/
public static List<BigInteger> getNumPrimes(BigInteger numberOfPrimes){
ArrayList<BigInteger> primes = new ArrayList<>(); //Holds the prime numbers
boolean foundFactor = false; //A flag for whether a factor of the current number has been found
@@ -201,7 +251,13 @@ public class NumberAlgorithms{
}
//This function return true if the value passed to it is prime
//?This function return true if the value passed to it is prime
/**
* Determines if a given number is prime.
*
* @param possiblePrime the number to be checked for primality
* @return {@code true} if {@code possiblePrime} is a prime number, {@code false} otherwise
*/
public static boolean isPrime(long possiblePrime){
if(possiblePrime <= 3){
return possiblePrime > 1;
@@ -216,6 +272,12 @@ public class NumberAlgorithms{
}
return true;
}
/**
* Determines if a given number is prime.
*
* @param possiblePrime the number to be checked for primality
* @return {@code true} if {@code possiblePrime} is a prime number, {@code false} otherwise
*/
public static boolean isPrime(BigInteger possiblePrime){
if(possiblePrime.compareTo(BigInteger.valueOf(3)) <= 0){
return possiblePrime.compareTo(BigInteger.ONE) > 0;
@@ -232,10 +294,23 @@ public class NumberAlgorithms{
}
//This function returns all factors of goalNumber
//?This function returns all factors of goalNumber
/**
* Returns a list of prime factors of the specified number.
*
* @param goalNumber the number to factorize
* @return a list of prime factors of {@code goalNumber}
* @see #getFactors(long)
*/
public static List<Integer> getFactors(int goalNumber) throws InvalidResult{
return ArrayAlgorithms.longToInt(getFactors((long)goalNumber));
}
/**
* Returns a list of prime factors of the specified number.
*
* @param goalNumber the number to factorize
* @return a list of prime factors of {@code goalNumber}
*/
public static List<Long> getFactors(long goalNumber) throws InvalidResult{
//You need to get all the primes that could be factors of this number so you can test them
Double topPossiblePrime = Math.ceil(Math.sqrt(goalNumber));
@@ -270,6 +345,12 @@ public class NumberAlgorithms{
//Return the list of factors
return factors;
}
/**
* Returns a list of prime factors of the specified number.
*
* @param goalNumber the number to factorize
* @return a list of prime factors of {@code goalNumber}
*/
public static List<BigInteger> getFactors(BigInteger goalNumber) throws InvalidResult{
//You need to get all the primes that could be factors of this number so you can test them
BigInteger topPossiblePrime = goalNumber.sqrt().add(BigInteger.ONE);
@@ -306,10 +387,23 @@ public class NumberAlgorithms{
}
//This function returns all the divisors of goalNumber
//?This function returns all the divisors of goalNumber
/**
* Returns a list of divisors of the specified number.
*
* @param goalNumber the number to find divisors for
* @return a list of divisors of {@code goalNumber}
* @see #getDivisors(long)
*/
public static List<Integer> getDivisors(int goalNumber){
return ArrayAlgorithms.longToInt(getDivisors((long)goalNumber));
}
/**
* Returns a list of divisors of the specified number.
*
* @param goalNumber the number to find divisors for
* @return a list of divisors of {@code goalNumber}
*/
public static List<Long> getDivisors(long goalNumber){
HashSet<Long> divisors = new HashSet<>();
//Start by checking that the number is positive
@@ -338,6 +432,12 @@ public class NumberAlgorithms{
//Return the list
return divisorList;
}
/**
* Returns a list of divisors of the specified number.
*
* @param goalNumber the number to find divisors for
* @return a list of divisors of {@code goalNumber}
*/
public static List<BigInteger> getDivisors(BigInteger goalNumber){
HashSet<BigInteger> divisors = new HashSet<>();
//Start by checking that the number is positive
@@ -367,10 +467,24 @@ public class NumberAlgorithms{
return divisorList;
}
//This function returns the goalSubscript'th Fibonacci number
//?This function returns the goalSubscript'th Fibonacci number
/**
* Returns the Fibonacci number at the specified position.
*
* @param goalSubscript the position of the desired Fibonacci number
* @return the Fibonacci number at position {@code goalSubscript}
* @see #getFib(long)
*/
public static int getFib(int goalSubscript){
return (int)getFib((long)goalSubscript);
}
/**
* Returns the Fibonacci number at the specified position.
*
* @param goalSubscript the position of the desired Fibonacci number
* @return the Fibonacci number at position {@code goalSubscript}
*/
public static long getFib(long goalSubscript){
//Setup the variables
long[] fibNums = {1L, 1L, 0L}; //A list to keep track of the Fibonacci numbers. It need only be 3 long because we only need the one we are working on and the last 2
@@ -389,6 +503,12 @@ public class NumberAlgorithms{
//Return the proper number. The location counter is 1 off of the subscript
return fibNums[(fibLoc - 1) % 3];
}
/**
* Returns the Fibonacci number at the specified position.
*
* @param goalSubscript the position of the desired Fibonacci number
* @return the Fibonacci number at position {@code goalSubscript}
*/
public static BigInteger getFib(BigInteger goalSubscript){
//Setup the variables
BigInteger[] fibNums = {BigInteger.valueOf(1), BigInteger.valueOf(1), BigInteger.valueOf(0)}; //A list to keep track of the Fibonacci numbers. It need only be 3 long because we only need the one we are working on and the last 2
@@ -408,10 +528,24 @@ public class NumberAlgorithms{
return fibNums[(fibLoc - 1) % 3];
}
//This function returns a list of all Fibonacci numbers <= goalNumber
//?This function returns a list of all Fibonacci numbers <= goalNumber
/**
* Returns a list of all Fibonacci numbers less than or equal to the specified number.
*
* @param goalNumber the upper limit for generating Fibonacci numbers
* @return a list of Fibonacci numbers less than or equal to {@code goalNumber}
* @see #getAllFib(long)
*/
public static List<Integer> getAllFib(int goalNumber){
return ArrayAlgorithms.longToInt(getAllFib((long) goalNumber));
}
/**
* Returns a list of all Fibonacci numbers less than or equal to the specified number.
*
* @param goalNumber the upper limit for generating Fibonacci numbers
* @return a list of Fibonacci numbers less than or equal to {@code goalNumber}
*/
public static List<Long> getAllFib(long goalNumber){
//Setup the variables
ArrayList<Long> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers
@@ -434,6 +568,12 @@ public class NumberAlgorithms{
fibNums.remove(fibNums.size() - 1);
return fibNums;
}
/**
* Returns a list of all Fibonacci numbers less than or equal to the specified number.
*
* @param goalNumber the upper limit for generating Fibonacci numbers
* @return a list of Fibonacci numbers less than or equal to {@code goalNumber}
*/
public static List<BigInteger> getAllFib(BigInteger goalNumber){
//Setup the variables
ArrayList<BigInteger> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers
@@ -457,10 +597,26 @@ public class NumberAlgorithms{
return fibNums;
}
//This function returns the factorial of the number passed to it
//?This function returns the factorial of the number passed to it
/**
* Calculates the factorial of the specified number.
*
* @param num the number to calculate the factorial for
* @return the factorial of {@code num}
* @throws IllegalArgumentException if {@code num} is negative
* @see #factorial(long)
*/
public static int factorial(int num) throws InvalidParameterException{
return (int)factorial((long)num);
}
/**
* Calculates the factorial of the specified number.
*
* @param num the number to calculate the factorial for
* @return the factorial of {@code num}
* @throws IllegalArgumentException if {@code num} is negative
*/
public static long factorial(long num) throws InvalidParameterException{
long fact = 1L; //The value of the factorial
@@ -475,6 +631,13 @@ public class NumberAlgorithms{
return fact;
}
/**
* Calculates the factorial of the specified number.
*
* @param num the number to calculate the factorial for
* @return the factorial of {@code num}
* @throws IllegalArgumentException if {@code num} is negative
*/
public static BigInteger factorial(BigInteger num) throws InvalidParameterException{
BigInteger fact = BigInteger.valueOf(1L);
@@ -490,10 +653,26 @@ public class NumberAlgorithms{
return fact;
}
//This function returns the GCD of the two numbers sent to it
//?This function returns the GCD of the two numbers sent to it
/**
* Calculates the greatest common divisor (GCD) of two numbers.
*
* @param num1 the first number
* @param num2 the second number
* @return the greatest common divisor of {@code num1} and {@code num2}
* @see #gcd(long, long)
*/
public static int gcd(int num1, int num2){
return (int)gcd((long)num1, (long)num2);
}
/**
* Calculates the greatest common divisor (GCD) of two numbers.
*
* @param num1 the first number
* @param num2 the second number
* @return the greatest common divisor of {@code num1} and {@code num2}
*/
public static long gcd(long num1, long num2){
while((num1 != 0) && (num2 != 0)){
if(num1 > num2){
@@ -505,6 +684,13 @@ public class NumberAlgorithms{
}
return num1 | num2;
}
/**
* Calculates the greatest common divisor (GCD) of two numbers.
*
* @param num1 the first number
* @param num2 the second number
* @return the greatest common divisor of {@code num1} and {@code num2}
*/
public static BigInteger gcd(BigInteger num1, BigInteger num2){
while(!num1.equals(BigInteger.ZERO) && !num2.equals(BigInteger.ZERO)){
if(num1.compareTo(num2) > 0){
@@ -517,11 +703,23 @@ public class NumberAlgorithms{
return num1.or(num2);
}
//Converts a number to its binary equivalent
//?Converts a number to its binary equivalent
/**
* Converts a number to its binary equivalent.
*
* @param num the number to convert
* @return the binary equivalent of {@code num}
*/
public static String toBin(long num){
//Convert the number to binary string
return Long.toBinaryString(num);
}
/**
* Converts a number to its binary equivalent.
*
* @param num the number to convert
* @return the binary equivalent of {@code num}
*/
public static String toBin(BigInteger num){
//Conver the number to binary string
return num.toString(2);

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/Stopwatch.java
//Matthew Ellison (Mattrixwv)
// Created: 03-01-19
//Modified: 04-13-23
//Modified: 08-11-24
//This file contains a class that is used to time the execution time of other programs
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -25,16 +25,49 @@ package com.mattrixwv;
import com.mattrixwv.exceptions.InvalidResult;
/**
* A simple stopwatch class to measure elapsed time in various units of resolution.
*
* <p>
* This class provides methods to start, stop, and reset a stopwatch, as well as retrieve the
* elapsed time in nanoseconds, microseconds, milliseconds, seconds, minutes, and hours. It
* also includes functionality to get the elapsed time as a formatted string in the most
* appropriate time unit.
* </p>
*/
public class Stopwatch{
/**
* The start time of the stopwatch in nanoseconds.
*/
private Long startTime;
/**
* The stop time of the stopwatch in nanoseconds.
*/
private Long stopTime;
//Constructor makes sure all values are set to defaults
//?Constructor makes sure all values are set to defaults
/**
* Constructs a new Stopwatch and initializes the start and stop times to {@code null}.
* This ensures that incorrect function calling order can be detected easily.
*/
public Stopwatch(){
//Make sure both values are null so it is easier to detect incorrect function calling order
startTime = null;
stopTime = null;
}
//Returns a long with the elapsed time in nanoseconds. Used by other functions to get the time before converting it to the correct resolution
//?Returns a long with the elapsed time in nanoseconds. Used by other functions to get the time before converting it to the correct resolution
/**
* Returns the elapsed time in nanoseconds.
* <p>
* If the stopwatch has not been started, it returns {@code 0L}. If the stopwatch has
* been started but not stopped, it returns the time elapsed since it was started.
* </p>
*
* @return the elapsed time in nanoseconds
*/
private Long getTime(){
if(startTime == null){
return 0L;
@@ -46,16 +79,37 @@ public class Stopwatch{
return stopTime - startTime;
}
}
//An enum that helps keep track of how many times the time has been reduced in the getStr function
//?An enum that helps keep track of how many times the time has been reduced in the getStr function
/**
* Enum to represent the time resolution for formatting the time string.
*/
private enum TIME_RESOLUTION{ NANOSECOND, MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR, ERROR }
//Simulates starting a stopwatch by saving the time
//?Simulates starting a stopwatch by saving the time
/**
* Starts the stopwatch by recording the current time in nanoseconds.
* <p>
* If the stopwatch was already running, the previous start time is overwritten.
* </p>
*/
public void start(){
//Make sure the stop time is reset to 0
stopTime = null;
//Get the time as close to returning from the function as possible
startTime = System.nanoTime();
}
//Simulates stopping a stopwatch by saving the time
//?Simulates stopping a stopwatch by saving the time
/**
* Stops the stopwatch by recording the current time in nanoseconds.
* <p>
* If the stopwatch has not been started, this method has no effect.
* </p>
*/
public void stop(){
//Set the stopTime as close to call time as possible
stopTime = System.nanoTime();
@@ -64,42 +118,114 @@ public class Stopwatch{
stopTime = null;
}
}
//Resets all variables in the stopwatch
//?Resets all variables in the stopwatch
/**
* Resets the stopwatch, clearing the start and stop times.
* <p>
* After calling this method, the stopwatch needs to be started again before measuring
* elapsed time.
* </p>
*/
public void reset(){
//Make sure all variables are reset correctly
startTime = null;
stopTime = null;
}
//Returns the time in nanoseconds
//?Returns the time in nanoseconds
/**
* Returns the elapsed time in nanoseconds.
*
* @return the elapsed time in nanoseconds as a {@code double}
*/
public double getNano(){
return getTime().doubleValue();
}
//Returns the time in microseconds
//?Returns the time in microseconds
/**
* Returns the elapsed time in microseconds.
*
* @return the elapsed time in microseconds as a {@code double}
*/
public double getMicro(){
return getTime().doubleValue() / 1000D;
}
//Returns the time in milliseconds
//?Returns the time in milliseconds
/**
* Returns the elapsed time in milliseconds.
*
* @return the elapsed time in milliseconds as a {@code double}
*/
public double getMilli(){
return getTime().doubleValue() / 1000000D;
}
//Returns the time in seconds
//?Returns the time in seconds
/**
* Returns the elapsed time in seconds.
*
* @return the elapsed time in seconds as a {@code double}
*/
public double getSecond(){
return getTime().doubleValue() / 1000000000D;
}
//Returns the time in minutes
//?Returns the time in minutes
/**
* Returns the elapsed time in minutes.
*
* @return the elapsed time in minutes as a {@code double}
*/
public double getMinute(){
return getTime().doubleValue() / 60000000000D;
}
//Returns the time in hours
//?Returns the time in hours
/**
* Returns the elapsed time in hours.
*
* @return the elapsed time in hours as a {@code double}
*/
public double getHour(){
return getTime().doubleValue() / 3600000000000D;
}
//Returns the time as a string at the 'best' resolution. (Goal is xxx.xxx)
//?Returns the time as a string at the 'best' resolution. (Goal is xxx.xxx)
/**
* Returns the elapsed time as a formatted string with the most appropriate resolution.
* <p>
* The method automatically selects the best time resolution to display the time in a
* human-readable format.
* </p>
*
* @return a formatted string representing the elapsed time
* @throws InvalidResult if the time resolution is invalid
*/
public String getStr() throws InvalidResult{
//Get the current duration from time
return getStr(getTime().doubleValue());
}
/**
* Returns a formatted string representing the given time in nanoseconds with the most
* appropriate resolution.
*
* @param nanoseconds the time in nanoseconds to format
* @return a formatted string representing the given time
* @throws InvalidResult if the time resolution is invalid
*/
public static String getStr(double nanoseconds) throws InvalidResult{
Double duration = nanoseconds;
//Reduce the number to the appropriate number of digits. (xxx.x).
@@ -145,6 +271,12 @@ public class Stopwatch{
return time;
}
/**
* Returns a string representation of the elapsed time in the most appropriate resolution.
*
* @return a string representation of the elapsed time
*/
@Override
public String toString(){
return getStr();

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/StringAlgorithms.java
//Matthew Ellison
// Created: 07-03-21
//Modified: 04-13-23
//Modified: 08-11-24
//This class contains algorithms for strings that I've found it useful to keep around
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -27,12 +27,38 @@ import java.util.Collections;
import java.util.List;
/**
* Utility class providing algorithms for manipulating and analyzing strings.
*
* <p>
* This class offers methods to generate permutations of a string, count occurrences of a character,
* check if a string is a palindrome, and determine if a string is pandigital.
* </p>
*/
public class StringAlgorithms{
/**
* Private constructor to prevent instantiation of this utility class.
*/
private StringAlgorithms(){}
//This is a function that creates all permutations of a string and returns a vector of those permutations.
//?This is a function that creates all permutations of a string and returns a vector of those permutations.
/**
* Generates all permutations of the given string.
*
* @param master the input string for which permutations are to be generated
* @return a list of all permutations of the input string
*/
public static List<String> getPermutations(String master){
return getPermutations(master, 0);
}
/**
* Generates permutations of the given string starting from the specified index.
*
* @param master the input string for which permutations are to be generated
* @param num the starting index for generating permutations
* @return a list of permutations generated from the specified starting index
*/
protected static ArrayList<String> getPermutations(String master, int num){
ArrayList<String> perms = new ArrayList<>();
//Check if the number is out of bounds
@@ -65,6 +91,15 @@ public class StringAlgorithms{
//Return the arraylist that was built
return perms;
}
/**
* Swaps two characters in the given string.
*
* @param str the string in which the characters are to be swapped
* @param first the index of the first character to be swapped
* @param second the index of the second character to be swapped
* @return a new string with the specified characters swapped
*/
private static String swapString(String str, int first, int second){
char[] tempStr = str.toCharArray();
char temp = tempStr[first];
@@ -73,16 +108,43 @@ public class StringAlgorithms{
return new String(tempStr);
}
//This function returns the number of times the character occurs in the string
//?This function returns the number of times the character occurs in the string
/**
* Counts the number of occurrences of a character in a string.
*
* @param str the string in which to count occurrences
* @param c the character whose occurrences are to be counted
* @return the number of times the character occurs in the string
*/
public static long findNumOccurrence(String str, char c){
return str.chars().filter(ch -> ch == c).count();
}
//Returns true if the string passed in is a palindrome
//?Returns true if the string passed in is a palindrome
/**
* Checks if a string is a palindrome.
*
* @param str the string to be checked
* @return {@code true} if the string is a palindrome, {@code false} otherwise
*/
public static boolean isPalindrome(String str){
String rev = new StringBuilder(str).reverse().toString();
return str.equals(rev);
}
//Returns true if the string passed to it is a pandigital
//?Returns true if the string passed to it is a pandigital
/**
* Checks if a string is pandigital within a given range of characters.
*
* @param str the string to be checked
* @param bottom the starting character of the pandigital range
* @param top the ending character of the pandigital range
* @return {@code true} if the string is pandigital within the given range, {@code false} otherwise
*/
public static boolean isPandigital(String str, char bottom, char top){
//Return false if top < bottom
if(top < bottom){
@@ -104,6 +166,12 @@ public class StringAlgorithms{
//If the function has reached this part it has passed all of the falsifying tests
return true;
}
/**
* Checks if a string is pandigital with respect to the digits 1 through 9.
*
* @param str the string to be checked
* @return {@code true} if the string is pandigital from '1' to '9', {@code false} otherwise
*/
public static boolean isPandigital(String str){
return isPandigital(str, '1', '9');
}

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/com/mattrixwv/Triple.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//Modified: 08-11-24
//This class implements a triplet of variables
/*
Copyright (C) 2022 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -22,27 +22,80 @@ Copyright (C) 2022 Matthew Ellison
package com.mattrixwv;
/**
* A generic class representing a set of three elements.
*
* <p>
* This class holds three values of potentially different types and provides methods to access them.
* </p>
*
* @param <T> the type of the first element
* @param <U> the type of the second element
* @param <V> the type of the third element
*/
public class Triple<T, U, V>{
/**
* The first element of the triple
*/
private T a;
/**
* The second element of the triple
*/
private U b;
/**
* The third element of the triple
*/
private V c;
/**
* Constructs a new Triple with the specified values.
*
* @param a the first element of the triple
* @param b the second element of the triple
* @param c the third element of the triple
*/
public Triple(T a, U b, V c){
this.a = a;
this.b = b;
this.c = c;
}
/**
* Returns the first element of the triple.
*
* @return the first element of the triple
*/
public T getA(){
return a;
}
/**
* Returns the second element of the triple.
*
* @return the second element of the triple
*/
public U getB(){
return b;
}
/**
* Returns the third element of the triple.
*
* @return the third element of the triple
*/
public V getC(){
return c;
}
/**
* Compares the specified object with this Triple for equality.
*
* <p>
* Returns {@code true} if and only if the specified object is also a Triple, and all
* corresponding pairs of elements in the two Triples are equal.
* </p>
*
* @param o the object to be compared for equality with this Triple
* @return {@code true} if the specified object is equal to this Triple, {@code false} otherwise
*/
@Override
public boolean equals(Object o){
if(this == o){
@@ -55,10 +108,27 @@ public class Triple<T, U, V>{
return false;
}
}
/**
* Returns the hash code value for this Triple.
*
* @return the hash code value for this Triple
*/
@Override
public int hashCode(){
return a.hashCode() + b.hashCode() * c.hashCode();
}
/**
* Returns a string representation of the Triple.
*
* <p>
* The string representation consists of the string representations of the three elements,
* separated by commas and enclosed in square brackets.
* </p>
*
* @return a string representation of the Triple
*/
@Override
public String toString(){
return "[" + a.toString() + ", " + b.toString() + ", " + c.toString() + "]";

View File

@@ -1,23 +1,59 @@
//JavaClasses/src/main/java/mattrixwv/Exceptions/InvalidResult.java
//Matthew Ellison
// Created: 08-24-20
//Modified: 04-13-23
//Modified: 08-11-24
//This is an exception for an invalid result out of one of my algorithms
package com.mattrixwv.exceptions;
/**
* The {@code InvalidResult} class extends {@code RuntimeException} and is used to indicate
* that an invalid result has occurred. It provides several constructors to create exceptions
* with a custom message and/or cause.
*
* <p>This class is a runtime exception, meaning it is unchecked and does not need to be declared
* in a method or constructor's {@code throws} clause.</p>
*
* @see RuntimeException
*/
public class InvalidResult extends RuntimeException{
private static final long serialVersionUID = 1L;
/**
* Constructs a new runtime exception with {@code null} as its detail message.
* The cause is not initialized and may subsequently be initialized by a call to {@link #initCause}.
*/
public InvalidResult(){
super();
}
/**
* Constructs a new runtime exception with the specified detail message. The cause is not initialized,
* and may subsequently be initialized by a call to {@link #initCause}.
*
* @param msg the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
public InvalidResult(String msg){
super(msg);
}
/**
* Constructs a new runtime exception with the specified cause and a detail message of
* {@code (cause == null ? null : cause.toString())} (which typically contains the class
* and detail message of {@code cause}).
*
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
* A {@code null} value is permitted and indicates that the cause is nonexistent or unknown.
*/
public InvalidResult(Throwable cause){
super(cause);
}
/**
* Constructs a new runtime exception with the specified detail message and cause.
*
* <p>Note that the detail message associated with {@code cause} is not automatically incorporated
* in this runtime exception's detail message.</p>
*
* @param msg the detail message (which is saved for later retrieval by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method).
* A {@code null} value is permitted and indicates that the cause is nonexistent or unknown.
*/
public InvalidResult(String msg, Throwable cause){
super(msg, cause);
}

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/HexagonalNumberGenerator.java
//Matthew Ellison
// Created: 08-20-22
//Modified: 04-13-23
//Modified: 08-11-24
//This class generates hexagonal numbers
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -26,18 +26,48 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A generator for hexagonal numbers, which implements the {@link Iterator} interface.
*
* <p>
* Hexagonal numbers are figurate numbers that represent hexagons. The n-th hexagonal number is given by
* the formula: H(n) = 2n^2 - n.
* </p>
*
* <p>
* This generator allows iteration over hexagonal numbers starting from the first.
* </p>
*/
public class HexagonalNumberGenerator implements Iterator<Long>{
/**
* The number to generate the next hexagonal number from.
*/
protected long num;
/**
* Constructs a new HexagonalNumberGenerator starting from the first hexagonal number.
*/
public HexagonalNumberGenerator(){
num = 1L;
}
/**
* Checks if there is a next hexagonal number that can be generated without overflow.
*
* @return {@code true} if the next hexagonal number can be generated, {@code false} otherwise
*/
@Override
public boolean hasNext(){
return (2 * num * num) > num;
}
/**
* Returns the next hexagonal number.
*
* @return the next hexagonal number
* @throws NoSuchElementException if the next hexagonal number would cause overflow
*/
@Override
public Long next(){
//If the number will result in an overflow throw an exception
@@ -52,6 +82,12 @@ public class HexagonalNumberGenerator implements Iterator<Long>{
return hexNum;
}
/**
* Checks if a given number is a hexagonal number.
*
* @param x the number to check
* @return {@code true} if the number is hexagonal, {@code false} otherwise
*/
public static boolean isHexagonal(Long x){
Long n = Math.round((Math.sqrt(1.0D + (8L * x)) + 1L) / 4L);
return ((2L * n * n) - n) == x;

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java
//Mattrixwv
// Created: 08-20-22
//Modified: 04-13-23
//Modified: 08-11-24
//This class generates pentagonal numbers
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -26,18 +26,47 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A generator for pentagonal numbers, which implements the {@link Iterator} interface.
*
* <p>
* Pentagonal numbers are figurate numbers that represent pentagons. The n-th pentagonal number is given by
* the formula: P(n) = (3n^2 - n) / 2.
* </p>
*
* <p>
* This generator allows iteration over pentagonal numbers starting from the first.
* </p>
*/
public class PentagonalNumberGenerator implements Iterator<Long>{
/**
* The number to generate the next pentagonal number from.
*/
protected long num;
/**
* Constructs a new PentagonalNumberGenerator starting from the first pentagonal number.
*/
public PentagonalNumberGenerator(){
num = 1L;
}
/**
* Checks if there is a next pentagonal number that can be generated without overflow.
*
* @return {@code true} if the next pentagonal number can be generated, {@code false} otherwise
*/
@Override
public boolean hasNext(){
return (3L * num * num) > num;
}
/**
* Returns the next pentagonal number.
*
* @return the next pentagonal number
* @throws NoSuchElementException if the next pentagonal number would cause overflow
*/
@Override
public Long next(){
if(!hasNext()){
@@ -49,6 +78,12 @@ public class PentagonalNumberGenerator implements Iterator<Long>{
return pentNum;
}
/**
* Checks if a given number is a pentagonal number.
*
* @param x the number to check
* @return {@code true} if the number is pentagonal, {@code false} otherwise
*/
public static boolean isPentagonal(Long x){
Long n = Math.round((Math.sqrt(1.0D + (24L * x)) + 1L) / 6L);
return (((3L * n * n) - n) / 2L) == x;

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenes.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 04-13-23
//Modified: 08-11-24
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -30,21 +30,62 @@ import java.util.Map;
import java.util.NoSuchElementException;
/**
* A generator for prime numbers using the Sieve of Eratosthenes algorithm, which implements the {@link Iterator} interface.
*
* <p>
* This implementation generates prime numbers in an incremental fashion using a modified version of the Sieve of Eratosthenes algorithm.
* The algorithm uses a map to keep track of the multiples of found prime numbers to efficiently determine the next prime.
* </p>
*/
public class SieveOfEratosthenes implements Iterator<Long>{
/**
* The next possible prime to be found
*/
protected long possiblePrime;
/**
* A dictionary of the primes that have been found and their next multiple
*/
protected Map<Long, ArrayList<Long>> dict;
/**
* Constructs a new SieveOfEratosthenes instance with an empty prime dictionary
* and starts the search from the first possible prime number, 2.
*/
public SieveOfEratosthenes(){
dict = new HashMap<>();
possiblePrime = 2;
}
/**
* Indicates whether there is a next prime number available.
*
* <p>
* This method always returns {@code true} as the iterator is designed to
* generate primes indefinitely.
* </p>
*
* @return {@code true}, as the iterator can generate an infinite number of primes
*/
@Override
public boolean hasNext(){
return true;
}
/**
* Returns the next prime number.
*
* <p>
* The method generates the next prime number by checking and updating the
* internal map of known multiples. The first prime returned is 2, and subsequent
* primes are found by incrementing the possible prime number and checking its
* primality using the map.
* </p>
*
* @return the next prime number
* @throws NoSuchElementException if the next prime cannot be represented by a {@code long}
*/
@Override
public Long next(){
long prime;

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java
//Matthew Ellison
// Created: 06-30-21
//Modified: 04-13-23
//Modified: 08-11-24
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -28,23 +28,65 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* A generator for prime numbers using the Sieve of Eratosthenes algorithm, which implements the {@link Iterator} interface.
*
* <p>
* This implementation generates prime numbers in an incremental fashion using a modified version of the Sieve of Eratosthenes algorithm.
* The algorithm uses a map to keep track of the multiples of found prime numbers to efficiently determine the next prime.
* </p>
*/
public class SieveOfEratosthenesBig implements Iterator<BigInteger>{
/**
* The next possible prime to be found
*/
protected BigInteger possiblePrime;
/**
* A dictionary of the primes that have been found and their next multiple
*/
protected Map<BigInteger, ArrayList<BigInteger>> dict;
/**
* Constructs a new SieveOfEratosthenes instance with an empty prime dictionary
* and starts the search from the first possible prime number, 2.
*/
public SieveOfEratosthenesBig(){
dict = new HashMap<>();
possiblePrime = BigInteger.TWO;
}
/**
* Indicates whether there is a next prime number available.
*
* <p>
* This method always returns {@code true} as the iterator is designed to
* generate primes indefinitely.
* </p>
*
* @return {@code true}, as the iterator can generate an infinite number of primes
*/
@Override
public boolean hasNext(){
return true;
}
/**
* Returns the next prime number.
*
* <p>
* The method generates the next prime number by checking and updating the
* internal map of known multiples. The first prime returned is 2, and subsequent
* primes are found by incrementing the possible prime number and checking its
* primality using the map.
* </p>
*
* @return the next prime number
* @throws NoSuchElementException if the next prime cannot be represented by a {@code long}
*/
@Override
public BigInteger next(){
BigInteger prime;
@@ -72,6 +114,10 @@ public class SieveOfEratosthenesBig implements Iterator<BigInteger>{
//Delete the current entry
dict.remove(possiblePrime);
}
//Protect against overflows
if(possiblePrime.compareTo(BigInteger.ZERO) < 0){
throw new NoSuchElementException("the next prime cannot be described by a long");
}
//Save that the number is a prime
prime = possiblePrime;
//Add the next entry to the prime dictionary

View File

@@ -1,10 +1,10 @@
//JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java
//Mattrixwv
// Created: 08-20-22
//Modified: 04-13-23
//Modified: 08-11-24
//This class generates triangular numbers
/*
Copyright (C) 2023 Matthew Ellison
Copyright (C) 2024 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
@@ -26,19 +26,48 @@ import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A generator for triangular numbers, which implements the {@link Iterator} interface.
*
* <p>
* Triangular numbers are figurate numbers that represent triangles. The n-th triangular number is given by
* the formula: T(n) = n(n + 1) / 2.
* </p>
*
* <p>
* This generator allows iteration over triangular numbers starting from the first.
* </p>
*/
public class TriangularNumberGenerator implements Iterator<Long>{
/**
* The number to generate the next triangular number from
*/
protected long num;
/**
* Constructs a new TriangularNumberGenerator starting from the first triangular number.
*/
public TriangularNumberGenerator(){
num = 1L;
}
/**
* Checks if there is a next triangular number that can be generated without overflow.
*
* @return {@code true} if the next triangular number can be generated, {@code false} otherwise
*/
@Override
public boolean hasNext(){
return ((num * num) + num) > num;
}
/**
* Returns the next triangular number.
*
* @return the next triangular number
* @throws NoSuchElementException if the next triangular number would cause overflow
*/
@Override
public Long next(){
if(!hasNext()){
@@ -50,6 +79,12 @@ public class TriangularNumberGenerator implements Iterator<Long>{
return newNum;
}
/**
* Checks if a given number is a triangular number.
*
* @param x the number to check
* @return {@code true} if the number is triangular, {@code false} otherwise
*/
public static boolean isTriangular(Long x){
Long n = Math.round((Math.sqrt(1.0D + (8L * x)) - 1L) / 2L);
return (((n * n) + n) / 2L) == x;