mirror of
https://bitbucket.org/Mattrixwv/javaclasses.git
synced 2025-12-07 07:23:57 -05:00
Added number generators
This commit is contained in:
138
src/main/java/com/mattrixwv/ArrayAlgorithms.java
Normal file
138
src/main/java/com/mattrixwv/ArrayAlgorithms.java
Normal file
@@ -0,0 +1,138 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/ArrayAlgorithms.java
|
||||
//Matthew Ellison
|
||||
// Created: 07-03-21
|
||||
//Modified: 06-25-22
|
||||
//This class contains algorithms for vectors that I've found it useful to keep around
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv;
|
||||
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.StringJoiner;
|
||||
|
||||
|
||||
public class ArrayAlgorithms{
|
||||
private ArrayAlgorithms(){}
|
||||
//This function returns the sum of all elements in the list
|
||||
public static int getSum(Iterable<Integer> nums){
|
||||
//Setup the variables
|
||||
int sum = 0;
|
||||
|
||||
//Loop through every element in the list and add them together
|
||||
for(int num : nums){
|
||||
sum += num;
|
||||
}
|
||||
|
||||
//Return the sum of all elements
|
||||
return sum;
|
||||
}
|
||||
public static long getLongSum(Iterable<Long> nums){
|
||||
//Setup the variables
|
||||
long sum = 0;
|
||||
|
||||
//Loop through every element in the list and add them together
|
||||
for(long num : nums){
|
||||
sum += num;
|
||||
}
|
||||
|
||||
//Return the sum of all elements
|
||||
return sum;
|
||||
}
|
||||
public static BigInteger getBigSum(Iterable<BigInteger> nums){
|
||||
//Setup the variables
|
||||
BigInteger sum = BigInteger.ZERO;
|
||||
|
||||
//Loop through every element in the list and add them together
|
||||
for(BigInteger num : nums){
|
||||
sum = sum.add(num);
|
||||
}
|
||||
|
||||
//Return the sum of all elements
|
||||
return sum;
|
||||
}
|
||||
//This function returns the product of all elements in the list
|
||||
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()){
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Setup the variables
|
||||
int product = 1; //Start at 1 because x * 1 = x
|
||||
|
||||
//Loop through every element in the list and multiply them together
|
||||
for(int num : nums){
|
||||
product *= num;
|
||||
}
|
||||
|
||||
//Return the product of all elements
|
||||
return product;
|
||||
}
|
||||
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()){
|
||||
return 0L;
|
||||
}
|
||||
|
||||
//Setup the variables
|
||||
long product = 1L; //Start at 1 because x * 1 = x
|
||||
|
||||
//Loop through every element in the list and multiply them together
|
||||
for(long num : nums){
|
||||
product *= num;
|
||||
}
|
||||
|
||||
//Return the product of all elements
|
||||
return product;
|
||||
}
|
||||
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()){
|
||||
return BigInteger.valueOf(0);
|
||||
}
|
||||
|
||||
//Setup the variables
|
||||
BigInteger product = BigInteger.valueOf(1); //Start at 1 because x * 1 = x
|
||||
|
||||
//Loop through every element in the list and multiply them together
|
||||
for(BigInteger num : nums){
|
||||
product = product.multiply(num);
|
||||
}
|
||||
|
||||
//Return the product of all elements
|
||||
return product;
|
||||
}
|
||||
//Print a list
|
||||
public static <T> String printList(Iterable<T> list){
|
||||
StringJoiner returnString = new StringJoiner(", ", "[", "]");
|
||||
for(T obj : list){
|
||||
returnString.add(obj.toString());
|
||||
}
|
||||
return returnString.toString();
|
||||
}
|
||||
//Convert lists
|
||||
public static List<Integer> longToInt(List<Long> originalList){
|
||||
ArrayList<Integer> newList = new ArrayList<>(originalList.size());
|
||||
for(Long num : originalList){
|
||||
newList.add(num.intValue());
|
||||
}
|
||||
return newList;
|
||||
}
|
||||
}
|
||||
529
src/main/java/com/mattrixwv/NumberAlgorithms.java
Normal file
529
src/main/java/com/mattrixwv/NumberAlgorithms.java
Normal file
@@ -0,0 +1,529 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/NumberAlgorithms.java
|
||||
//Matthew Ellison
|
||||
// Created: 07-03-21
|
||||
//Modified: 06-25-22
|
||||
//This class contains algorithms for numbers that I've found it useful to keep around
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv;
|
||||
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.InvalidParameterException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
|
||||
import com.mattrixwv.exceptions.InvalidResult;
|
||||
|
||||
|
||||
public class NumberAlgorithms{
|
||||
private NumberAlgorithms(){}
|
||||
|
||||
public static final String FACTORIAL_NEGATIVE_MESSAGE = "n! cannot be negative";
|
||||
|
||||
//This function returns a list with all the prime numbers <= goalNumber
|
||||
public static List<Integer> getPrimes(int goalNumber){
|
||||
return ArrayAlgorithms.longToInt(getPrimes((long) 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
|
||||
|
||||
//If the numebr is 0 or negative return an empty list
|
||||
if(goalNumber <= 1){
|
||||
return primes;
|
||||
}
|
||||
//Otherwise the number is at least 2, so 2 should be added to the list
|
||||
else{
|
||||
primes.add(2L);
|
||||
}
|
||||
|
||||
//We cna now start at 3 and skipp 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));
|
||||
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
|
||||
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt) <= topPossibleFactor.intValue());++primesCnt){
|
||||
if((possiblePrime % primes.get(primesCnt)) == 0){
|
||||
foundFactor = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//If you didn't find a factor then the current number must be prime
|
||||
if(!foundFactor){
|
||||
primes.add(possiblePrime);
|
||||
}
|
||||
else{
|
||||
foundFactor = false;
|
||||
}
|
||||
}
|
||||
|
||||
//Sort the list before returning it
|
||||
Collections.sort(primes);
|
||||
return primes;
|
||||
}
|
||||
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
|
||||
|
||||
//If the number is 1, 0 or negative return an empty list
|
||||
if(goalNumber.compareTo(BigInteger.valueOf(1)) <= 0){
|
||||
return primes;
|
||||
}
|
||||
//Otherwise the number is at least 2, so 2 should be added to the list
|
||||
else{
|
||||
primes.add(BigInteger.valueOf(2));
|
||||
}
|
||||
|
||||
//We can now start at 3 and skip all even numbers, because they cannot be prime
|
||||
for(BigInteger possiblePrime = BigInteger.valueOf(3);possiblePrime.compareTo(goalNumber) <= 0;possiblePrime = possiblePrime.add(BigInteger.valueOf(2))){
|
||||
//Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
|
||||
BigInteger topPossibleFactor = possiblePrime.sqrt().add(BigInteger.valueOf(1));
|
||||
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
|
||||
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt).compareTo(topPossibleFactor) <= 0);++primesCnt){
|
||||
if((possiblePrime.mod(primes.get(primesCnt))) == BigInteger.valueOf(0)){
|
||||
foundFactor = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//If you didn't find a factor then the current number must be prime
|
||||
if(!foundFactor){
|
||||
primes.add(possiblePrime);
|
||||
}
|
||||
else{
|
||||
foundFactor = false;
|
||||
}
|
||||
}
|
||||
|
||||
//Sort the list before returning it
|
||||
Collections.sort(primes);
|
||||
return primes;
|
||||
}
|
||||
|
||||
|
||||
//This function gets a certain number of primes
|
||||
public static List<Integer> getNumPrimes(int numberOfPrimes){
|
||||
return ArrayAlgorithms.longToInt(getNumPrimes((long)numberOfPrimes));
|
||||
}
|
||||
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
|
||||
|
||||
//If the number is 0 or negative return an empty list
|
||||
if(numberOfPrimes < 1){
|
||||
return primes;
|
||||
}
|
||||
//Otherwise the number is at least 2, so 2 should be added to the list
|
||||
else{
|
||||
primes.add(2L);
|
||||
}
|
||||
|
||||
//We can now start at 3 and skip all even numbers, because they cannot be prime
|
||||
for(long possiblePrime = 3L;primes.size() < numberOfPrimes;possiblePrime += 2L){
|
||||
//Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
|
||||
Double topPossibleFactor = Math.ceil(Math.sqrt(possiblePrime));
|
||||
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
|
||||
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt) <= topPossibleFactor.intValue());++primesCnt){
|
||||
if((possiblePrime % primes.get(primesCnt)) == 0){
|
||||
foundFactor = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//If you didn't find a factor then the current number must be prime
|
||||
if(!foundFactor){
|
||||
primes.add(possiblePrime);
|
||||
}
|
||||
else{
|
||||
foundFactor = false;
|
||||
}
|
||||
}
|
||||
|
||||
//Sort the list before returning it
|
||||
Collections.sort(primes);
|
||||
return primes;
|
||||
}
|
||||
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
|
||||
|
||||
//If the number is 0 or negative return an empty list
|
||||
if(numberOfPrimes.compareTo(BigInteger.valueOf(1)) < 0){
|
||||
return primes;
|
||||
}
|
||||
//Otherwise the number is at least 2, so 2 should be added to the list
|
||||
else{
|
||||
primes.add(BigInteger.valueOf(2));
|
||||
}
|
||||
|
||||
//We can now start at 3 and skip all even numbers, because they cannot be prime
|
||||
for(BigInteger possiblePrime = BigInteger.valueOf(3);numberOfPrimes.compareTo((BigInteger.valueOf(primes.size()))) > 0;possiblePrime = possiblePrime.add(BigInteger.valueOf(2))){
|
||||
//Check all current primes, up to sqrt(possiblePrime), to see if there is a divisor
|
||||
BigInteger topPossibleFactor = possiblePrime.sqrt().add(BigInteger.valueOf(1));
|
||||
//We can safely assume that there will be at least 1 element in the primes list because of 2 being added before this
|
||||
for(int primesCnt = 0;(primesCnt < primes.size()) && (primes.get(primesCnt).compareTo(topPossibleFactor) <= 0);++primesCnt){
|
||||
if((possiblePrime.mod(primes.get(primesCnt))) == BigInteger.valueOf(0)){
|
||||
foundFactor = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//If you didn't find a factor then the current number must be prime
|
||||
if(!foundFactor){
|
||||
primes.add(possiblePrime);
|
||||
}
|
||||
else{
|
||||
foundFactor = false;
|
||||
}
|
||||
}
|
||||
|
||||
//Sort the list before returning it
|
||||
Collections.sort(primes);
|
||||
return primes;
|
||||
}
|
||||
|
||||
|
||||
//This function return true if the value passed to it is prime
|
||||
public static boolean isPrime(long possiblePrime){
|
||||
if(possiblePrime <= 3){
|
||||
return possiblePrime > 1;
|
||||
}
|
||||
else if(((possiblePrime % 2) == 0) || ((possiblePrime % 3) == 0)){
|
||||
return false;
|
||||
}
|
||||
for(long cnt = 5;(cnt * cnt) <= possiblePrime;cnt += 6){
|
||||
if(((possiblePrime % cnt) == 0) || ((possiblePrime % (cnt + 2)) == 0)){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public static boolean isPrime(BigInteger possiblePrime){
|
||||
if(possiblePrime.compareTo(BigInteger.valueOf(3)) <= 0){
|
||||
return possiblePrime.compareTo(BigInteger.ONE) > 0;
|
||||
}
|
||||
else if(possiblePrime.mod(BigInteger.TWO).equals(BigInteger.ZERO) || possiblePrime.mod(BigInteger.valueOf(3)).equals(BigInteger.ZERO)){
|
||||
return false;
|
||||
}
|
||||
for(BigInteger cnt = BigInteger.valueOf(5);(cnt.multiply(cnt)).compareTo(possiblePrime) <= 0;cnt = cnt.add(BigInteger.valueOf(6))){
|
||||
if(possiblePrime.mod(cnt).equals(BigInteger.ZERO) || possiblePrime.mod(cnt.add(BigInteger.TWO)).equals(BigInteger.ZERO)){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
//This function returns all factors of goalNumber
|
||||
public static List<Integer> getFactors(int goalNumber) throws InvalidResult{
|
||||
return ArrayAlgorithms.longToInt(getFactors((long)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));
|
||||
List<Long> primes = getPrimes(topPossiblePrime.longValue());
|
||||
ArrayList<Long> factors = new ArrayList<>();
|
||||
|
||||
//You need to step through each prime and see if it is a factor in the number
|
||||
for(int cnt = 0;cnt < primes.size();){
|
||||
//If the prime is a factor you need to add it to the factor list
|
||||
if((goalNumber % primes.get(cnt)) == 0){
|
||||
factors.add(primes.get(cnt));
|
||||
goalNumber /= primes.get(cnt);
|
||||
}
|
||||
//Otherwise advance the location in primes you are looking at
|
||||
//By not advancing if the prime is a factor you allow for multiple of the same prime number as a factor
|
||||
else{
|
||||
++cnt;
|
||||
}
|
||||
}
|
||||
|
||||
//If you didn't get any factors the number itself must be a prime
|
||||
if(factors.isEmpty()){
|
||||
factors.add(goalNumber);
|
||||
goalNumber /= goalNumber;
|
||||
}
|
||||
|
||||
//If for some reason the goalNumber is not 1 throw an error
|
||||
if(goalNumber != 1){
|
||||
throw new InvalidResult("The factor was not 1: " + goalNumber);
|
||||
}
|
||||
|
||||
//Return the list of factors
|
||||
return factors;
|
||||
}
|
||||
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();
|
||||
List<BigInteger> primes = getPrimes(topPossiblePrime);
|
||||
ArrayList<BigInteger> factors = new ArrayList<>();
|
||||
|
||||
//You need to step through each prime and see if it is a factor in the number
|
||||
for(int cnt = 0;cnt < primes.size();){
|
||||
//If the prime is a factor you need to add it to the factor list
|
||||
if((goalNumber.mod(primes.get(cnt))).compareTo(BigInteger.valueOf(0)) == 0){
|
||||
factors.add(primes.get(cnt));
|
||||
goalNumber = goalNumber.divide(primes.get(cnt));
|
||||
}
|
||||
//Otherwise advance the location in primes you are looking at
|
||||
//By not advancing if the prime is a factor you allow for multiple of the same prime number as a factor
|
||||
else{
|
||||
++cnt;
|
||||
}
|
||||
}
|
||||
|
||||
//If you didn't get any factors the number itself must be a prime
|
||||
if(factors.isEmpty()){
|
||||
factors.add(goalNumber);
|
||||
goalNumber = goalNumber.divide(goalNumber);
|
||||
}
|
||||
|
||||
//If for some reason the goalNumber is not 1 throw an error
|
||||
if(!goalNumber.equals(BigInteger.ONE)){
|
||||
throw new InvalidResult("The factor was not 1: " + goalNumber);
|
||||
}
|
||||
|
||||
//Return the list of factors
|
||||
return factors;
|
||||
}
|
||||
|
||||
|
||||
//This function returns all the divisors of goalNumber
|
||||
public static List<Integer> getDivisors(int goalNumber){
|
||||
return ArrayAlgorithms.longToInt(getDivisors((long)goalNumber));
|
||||
}
|
||||
public static List<Long> getDivisors(long goalNumber){
|
||||
HashSet<Long> divisors = new HashSet<>();
|
||||
//Start by checking that the number is positive
|
||||
if(goalNumber <= 0){
|
||||
return new ArrayList<>();
|
||||
}
|
||||
else{
|
||||
divisors.add(1L);
|
||||
divisors.add(goalNumber);
|
||||
}
|
||||
|
||||
//Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly
|
||||
Double topPossibleDivisor = Math.ceil(Math.sqrt(goalNumber));
|
||||
for(long possibleDivisor = 2L;possibleDivisor <= topPossibleDivisor;++possibleDivisor){
|
||||
//If you find one add it and the number it creates to the list
|
||||
if((goalNumber % possibleDivisor) == 0){
|
||||
long possibleDivisor2 = goalNumber / possibleDivisor;
|
||||
divisors.add(possibleDivisor);
|
||||
divisors.add(possibleDivisor2);
|
||||
}
|
||||
}
|
||||
|
||||
ArrayList<Long> divisorList = new ArrayList<>(divisors);
|
||||
//Sort the list before returning it for neatness
|
||||
Collections.sort(divisorList);
|
||||
//Return the list
|
||||
return divisorList;
|
||||
}
|
||||
public static List<BigInteger> getDivisors(BigInteger goalNumber){
|
||||
HashSet<BigInteger> divisors = new HashSet<>();
|
||||
//Start by checking that the number is positive
|
||||
if(goalNumber.compareTo(BigInteger.valueOf(0)) <= 0){
|
||||
return new ArrayList<>();
|
||||
}
|
||||
else{
|
||||
divisors.add(BigInteger.valueOf(1));
|
||||
divisors.add(goalNumber);
|
||||
}
|
||||
|
||||
//Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly
|
||||
BigInteger topPossibleDivisor = goalNumber.sqrt();
|
||||
for(BigInteger possibleDivisor = BigInteger.TWO;possibleDivisor.compareTo(topPossibleDivisor) <= 0;possibleDivisor = possibleDivisor.add(BigInteger.valueOf(1))){
|
||||
//If you find one add it and the number it creates to the list
|
||||
if(goalNumber.mod(possibleDivisor).equals(BigInteger.valueOf(0))){
|
||||
BigInteger possibleDivisor2 = goalNumber.divide(possibleDivisor);
|
||||
divisors.add(possibleDivisor);
|
||||
divisors.add(possibleDivisor2);
|
||||
}
|
||||
}
|
||||
|
||||
ArrayList<BigInteger> divisorList = new ArrayList<>(divisors);
|
||||
//Sort the list before returning it for neatness
|
||||
Collections.sort(divisorList);
|
||||
//Return the list
|
||||
return divisorList;
|
||||
}
|
||||
|
||||
//This function returns the goalSubscript'th Fibonacci number
|
||||
public static int getFib(int goalSubscript){
|
||||
return (int)getFib((long)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
|
||||
|
||||
//If the number is <= 0 return 0
|
||||
if(goalSubscript <= 0){
|
||||
return 0L;
|
||||
}
|
||||
|
||||
//Loop through the list, generating Fibonacci numbers until it finds the correct subscript
|
||||
int fibLoc;
|
||||
for(fibLoc = 2;fibLoc < goalSubscript;++fibLoc){
|
||||
fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3] + fibNums[(fibLoc - 2) % 3];
|
||||
}
|
||||
|
||||
//Return the proper number. The location counter is 1 off of the subscript
|
||||
return fibNums[(fibLoc - 1) % 3];
|
||||
}
|
||||
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
|
||||
|
||||
//If the number is <= 0 return 0
|
||||
if(goalSubscript.compareTo(BigInteger.valueOf(0)) <= 0){
|
||||
return BigInteger.valueOf(0);
|
||||
}
|
||||
|
||||
//Loop through the list, generating Fibonacci numbers until it finds the correct subscript
|
||||
int fibLoc;
|
||||
for(fibLoc = 2;goalSubscript.compareTo(BigInteger.valueOf(fibLoc)) > 0;++fibLoc){
|
||||
fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3].add(fibNums[(fibLoc - 2) % 3]);
|
||||
}
|
||||
|
||||
//Return the proper number. The location counter is 1 off of the subscript
|
||||
return fibNums[(fibLoc - 1) % 3];
|
||||
}
|
||||
|
||||
//This function returns a list of all Fibonacci numbers <= goalNumber
|
||||
public static List<Integer> getAllFib(int goalNumber){
|
||||
return ArrayAlgorithms.longToInt(getAllFib((long) goalNumber));
|
||||
}
|
||||
public static List<Long> getAllFib(long goalNumber){
|
||||
//Setup the variables
|
||||
ArrayList<Long> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers
|
||||
|
||||
//If the number is <= 0 return an empty list
|
||||
if(goalNumber <= 0){
|
||||
return fibNums;
|
||||
}
|
||||
|
||||
//This means that at least 2 1's are elements
|
||||
fibNums.add(1L);
|
||||
fibNums.add(1L);
|
||||
|
||||
//Loop to generate the rest of the Fibonacci numbers
|
||||
while(fibNums.get(fibNums.size() - 1) <= goalNumber){
|
||||
fibNums.add(fibNums.get(fibNums.size() - 1) + fibNums.get(fibNums.size() - 2));
|
||||
}
|
||||
|
||||
//At this point the most recent number is > goalNumber, so remove it and return the rest of the list
|
||||
fibNums.remove(fibNums.size() - 1);
|
||||
return fibNums;
|
||||
}
|
||||
public static List<BigInteger> getAllFib(BigInteger goalNumber){
|
||||
//Setup the variables
|
||||
ArrayList<BigInteger> fibNums = new ArrayList<>(); //A list to save the Fibonacci numbers
|
||||
|
||||
//If the number is <= 0 return an empty list
|
||||
if(goalNumber.compareTo(BigInteger.valueOf(0)) <= 0){
|
||||
return fibNums;
|
||||
}
|
||||
|
||||
//This means that at least 2 1's are elements
|
||||
fibNums.add(BigInteger.valueOf(1));
|
||||
fibNums.add(BigInteger.valueOf(1));
|
||||
|
||||
//Loop to generate the rest of the Fibonacci numbers
|
||||
while(fibNums.get(fibNums.size() - 1).compareTo(goalNumber) <= 0){
|
||||
fibNums.add(fibNums.get(fibNums.size() - 1).add(fibNums.get(fibNums.size() - 2)));
|
||||
}
|
||||
|
||||
//At this point the most recent number is > goalNumber, so remove it and return the rest of the list
|
||||
fibNums.remove(fibNums.size() - 1);
|
||||
return fibNums;
|
||||
}
|
||||
|
||||
//This function returns the factorial of the number passed to it
|
||||
public static int factorial(int num) throws InvalidParameterException{
|
||||
return (int)factorial((long)num);
|
||||
}
|
||||
public static long factorial(long num) throws InvalidParameterException{
|
||||
long fact = 1L; //The value of the factorial
|
||||
|
||||
//If the number passed in is < 0 throw an exception
|
||||
if(num < 0){
|
||||
throw new InvalidParameterException(FACTORIAL_NEGATIVE_MESSAGE);
|
||||
}
|
||||
//Loop through every number up to and including num and add the product to the factorial
|
||||
for(long cnt = 2L;cnt <= num;++cnt){
|
||||
fact *= cnt;
|
||||
}
|
||||
|
||||
return fact;
|
||||
}
|
||||
public static BigInteger factorial(BigInteger num) throws InvalidParameterException{
|
||||
BigInteger fact = BigInteger.valueOf(1L);
|
||||
|
||||
//If the number passed in is < 0 throw an exception
|
||||
if(num.compareTo(BigInteger.ZERO) < 0){
|
||||
throw new InvalidParameterException(FACTORIAL_NEGATIVE_MESSAGE);
|
||||
}
|
||||
//Loop through every number up to and including num and add the product to the factorial
|
||||
for(BigInteger cnt = BigInteger.TWO;cnt.compareTo(num) <= 0;cnt = cnt.add(BigInteger.ONE)){
|
||||
fact = fact.multiply(cnt);
|
||||
}
|
||||
|
||||
return fact;
|
||||
}
|
||||
|
||||
//This function returns the GCD of the two numbers sent to it
|
||||
public static int gcd(int num1, int num2){
|
||||
return (int)gcd((long)num1, (long)num2);
|
||||
}
|
||||
public static long gcd(long num1, long num2){
|
||||
while((num1 != 0) && (num2 != 0)){
|
||||
if(num1 > num2){
|
||||
num1 %= num2;
|
||||
}
|
||||
else{
|
||||
num2 %= num1;
|
||||
}
|
||||
}
|
||||
return num1 | num2;
|
||||
}
|
||||
public static BigInteger gcd(BigInteger num1, BigInteger num2){
|
||||
while(!num1.equals(BigInteger.ZERO) && !num2.equals(BigInteger.ZERO)){
|
||||
if(num1.compareTo(num2) > 0){
|
||||
num1 = num1.mod(num2);
|
||||
}
|
||||
else{
|
||||
num2 = num2.mod(num1);
|
||||
}
|
||||
}
|
||||
return num1.or(num2);
|
||||
}
|
||||
|
||||
//Converts a number to its binary equivalent
|
||||
public static String toBin(long num){
|
||||
//Convert the number to binary string
|
||||
return Long.toBinaryString(num);
|
||||
}
|
||||
public static String toBin(BigInteger num){
|
||||
//Conver the number to binary string
|
||||
return num.toString(2);
|
||||
}
|
||||
}
|
||||
153
src/main/java/com/mattrixwv/Stopwatch.java
Normal file
153
src/main/java/com/mattrixwv/Stopwatch.java
Normal file
@@ -0,0 +1,153 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/Stopwatch.java
|
||||
//Matthew Ellison (Mattrixwv)
|
||||
// Created: 03-01-19
|
||||
//Modified: 06-26-22
|
||||
//This file contains a class that is used to time the execution time of other programs
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv;
|
||||
|
||||
|
||||
import com.mattrixwv.exceptions.InvalidResult;
|
||||
|
||||
|
||||
public class Stopwatch{
|
||||
private Long startTime;
|
||||
private Long stopTime;
|
||||
//Constructor makes sure all values are set to defaults
|
||||
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
|
||||
private Long getTime(){
|
||||
if(startTime == null){
|
||||
return 0L;
|
||||
}
|
||||
else if(stopTime == null){
|
||||
return System.nanoTime() - startTime;
|
||||
}
|
||||
else{
|
||||
return stopTime - startTime;
|
||||
}
|
||||
}
|
||||
//An enum that helps keep track of how many times the time has been reduced in the getStr function
|
||||
private enum TIME_RESOLUTION{ NANOSECOND, MICROSECOND, MILLISECOND, SECOND, MINUTE, HOUR, ERROR }
|
||||
//Simulates starting a stopwatch by saving the time
|
||||
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
|
||||
public void stop(){
|
||||
//Set the stopTime as close to call time as possible
|
||||
stopTime = System.nanoTime();
|
||||
//If the startTime has not been set then reset stopTime
|
||||
if(startTime == null){
|
||||
stopTime = null;
|
||||
}
|
||||
}
|
||||
//Resets all variables in the stopwatch
|
||||
public void reset(){
|
||||
//Make sure all variables are reset correctly
|
||||
startTime = null;
|
||||
stopTime = null;
|
||||
}
|
||||
//Returns the time in nanoseconds
|
||||
public double getNano(){
|
||||
return getTime().doubleValue();
|
||||
}
|
||||
//Returns the time in microseconds
|
||||
public double getMicro(){
|
||||
return getTime().doubleValue() / 1000D;
|
||||
}
|
||||
//Returns the time in milliseconds
|
||||
public double getMilli(){
|
||||
return getTime().doubleValue() / 1000000D;
|
||||
}
|
||||
//Returns the time in seconds
|
||||
public double getSecond(){
|
||||
return getTime().doubleValue() / 1000000000D;
|
||||
}
|
||||
//Returns the time in minutes
|
||||
public double getMinute(){
|
||||
return getTime().doubleValue() / 60000000000D;
|
||||
}
|
||||
//Returns the time in hours
|
||||
public double getHour(){
|
||||
return getTime().doubleValue() / 3600000000000D;
|
||||
}
|
||||
//Returns the time as a string at the 'best' resolution. (Goal is xxx.xxx)
|
||||
public String getStr() throws InvalidResult{
|
||||
//Get the current duration from time
|
||||
return getStr(getTime().doubleValue());
|
||||
}
|
||||
|
||||
public static String getStr(double nanoseconds) throws InvalidResult{
|
||||
Double duration = nanoseconds;
|
||||
//Reduce the number to the appropriate number of digits. (xxx.x).
|
||||
//This loop works down to seconds
|
||||
TIME_RESOLUTION resolution;
|
||||
for(resolution = TIME_RESOLUTION.NANOSECOND;(resolution.ordinal() < TIME_RESOLUTION.SECOND.ordinal()) && (duration >= 1000);resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1]){
|
||||
duration /= 1000;
|
||||
}
|
||||
//Check if the duration needs reduced to minutes
|
||||
if((duration >= 120) && (resolution == TIME_RESOLUTION.SECOND)){
|
||||
//Reduce to minutes
|
||||
duration /= 60;
|
||||
resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1];
|
||||
|
||||
//Check if the duration needs reduced to hours
|
||||
if(duration >= 60){
|
||||
//Reduce to hours
|
||||
duration /= 60;
|
||||
resolution = TIME_RESOLUTION.values()[resolution.ordinal() + 1];
|
||||
}
|
||||
}
|
||||
|
||||
//Turn the number into a string
|
||||
int durationFraction = (int)Math.round(((duration % 1) * 1000));
|
||||
String time = String.format("%d.%03d", duration.intValue(), durationFraction);
|
||||
|
||||
//Tack on the appropriate suffix for resolution
|
||||
switch(resolution){
|
||||
case NANOSECOND: time += " nanoseconds"; break;
|
||||
case MICROSECOND: time += " microseconds"; break;
|
||||
case MILLISECOND: time += " milliseconds"; break;
|
||||
case SECOND: time += " seconds"; break;
|
||||
case MINUTE: time += " minutes"; break;
|
||||
case HOUR: time += " hours"; break;
|
||||
case ERROR:
|
||||
default: throw new InvalidResult("timeResolution was invalid");
|
||||
}
|
||||
//Return the string
|
||||
return time;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString(){
|
||||
try{
|
||||
return getStr();
|
||||
}
|
||||
catch(InvalidResult error){
|
||||
return "There was an error in getStr(): " + error;
|
||||
}
|
||||
}
|
||||
}
|
||||
110
src/main/java/com/mattrixwv/StringAlgorithms.java
Normal file
110
src/main/java/com/mattrixwv/StringAlgorithms.java
Normal file
@@ -0,0 +1,110 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/StringAlgorithms.java
|
||||
//Matthew Ellison
|
||||
// Created: 07-03-21
|
||||
//Modified: 10-11-21
|
||||
//This class contains algorithms for strings that I've found it useful to keep around
|
||||
/*
|
||||
Copyright (C) 2021 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class StringAlgorithms{
|
||||
private StringAlgorithms(){}
|
||||
//This is a function that creates all permutations of a string and returns a vector of those permutations.
|
||||
public static List<String> getPermutations(String master){
|
||||
return getPermutations(master, 0);
|
||||
}
|
||||
private static ArrayList<String> getPermutations(String master, int num){
|
||||
ArrayList<String> perms = new ArrayList<>();
|
||||
//Check if the number is out of bounds
|
||||
if((num >= master.length()) || (num < 0)){
|
||||
//Do nothing and return an empty arraylist
|
||||
}
|
||||
//If this is the last possible recurse just return the current string
|
||||
else if(num == (master.length() - 1)){
|
||||
perms.add(master);
|
||||
}
|
||||
//If there are more possible recurses, recurse with the current permutation
|
||||
else{
|
||||
ArrayList<String> temp = getPermutations(master, num + 1);
|
||||
perms.addAll(temp);
|
||||
//You need to swap the current letter with every possible letter after it
|
||||
//The ones needed to swap before will happen automatically when the function recurses
|
||||
for(int cnt = 1;(num + cnt) < master.length();++cnt){
|
||||
master = swapString(master, num, (num + cnt));
|
||||
temp = getPermutations(master, num + 1);
|
||||
perms.addAll(temp);
|
||||
master = swapString(master, num, (num + cnt));
|
||||
}
|
||||
|
||||
//The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning
|
||||
if(num == 0){
|
||||
Collections.sort(perms);
|
||||
}
|
||||
}
|
||||
|
||||
//Return the arraylist that was built
|
||||
return perms;
|
||||
}
|
||||
private static String swapString(String str, int first, int second){
|
||||
char[] tempStr = str.toCharArray();
|
||||
char temp = tempStr[first];
|
||||
tempStr[first] = tempStr[second];
|
||||
tempStr[second] = temp;
|
||||
|
||||
return new String(tempStr);
|
||||
}
|
||||
//This function returns 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
|
||||
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
|
||||
public static boolean isPandigital(String str, char bottom, char top){
|
||||
//Return false if top < bottom
|
||||
if(top < bottom){
|
||||
return false;
|
||||
}
|
||||
|
||||
//Return false if the wrong number of characters are in the string
|
||||
if(str.length() != (top - bottom + 1)){
|
||||
return false;
|
||||
}
|
||||
|
||||
//Make sure that all of the needed characters are in the string exactly one time
|
||||
for(char cnt = bottom;cnt <= top;++cnt){
|
||||
if(findNumOccurrence(str, cnt) != 1){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//If the function has reached this part it has passed all of the falsifying tests
|
||||
return true;
|
||||
}
|
||||
public static boolean isPandigital(String str){
|
||||
return isPandigital(str, '1', '9');
|
||||
}
|
||||
}
|
||||
67
src/main/java/com/mattrixwv/Triple.java
Normal file
67
src/main/java/com/mattrixwv/Triple.java
Normal file
@@ -0,0 +1,67 @@
|
||||
//JavaClasses/src/main/java/com/mattrixwv/Triple.java
|
||||
//Mattrixwv
|
||||
// Created: 08-20-22
|
||||
//Modified: 08-20-22
|
||||
//This class implements a triplet of variables
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv;
|
||||
|
||||
|
||||
public class Triple<T, U, V>{
|
||||
private T a;
|
||||
private U b;
|
||||
private V c;
|
||||
|
||||
public Triple(T a, U b, V c){
|
||||
this.a = a;
|
||||
this.b = b;
|
||||
this.c = c;
|
||||
}
|
||||
|
||||
public T getA(){
|
||||
return a;
|
||||
}
|
||||
public U getB(){
|
||||
return b;
|
||||
}
|
||||
public V getC(){
|
||||
return c;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o){
|
||||
if(this == o){
|
||||
return true;
|
||||
}
|
||||
else if(o instanceof Triple<?, ?, ?>){
|
||||
Triple<?, ?, ?> rightSide = (Triple<?, ?, ?>)o;
|
||||
return (a.equals(rightSide.a) && b.equals(rightSide.b) && c.equals(rightSide.c));
|
||||
}
|
||||
else{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public int hashCode(){
|
||||
return a.hashCode() + b.hashCode() * c.hashCode();
|
||||
}
|
||||
@Override
|
||||
public String toString(){
|
||||
return "[" + a.toString() + ", " + b.toString() + ", " + c.toString() + "]";
|
||||
}
|
||||
}
|
||||
17
src/main/java/com/mattrixwv/exceptions/InvalidResult.java
Normal file
17
src/main/java/com/mattrixwv/exceptions/InvalidResult.java
Normal file
@@ -0,0 +1,17 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/Exceptions/InvalidResult.java
|
||||
//Matthew Ellison
|
||||
// Created: 08-24-20
|
||||
//Modified: 08-24-20
|
||||
//This is an exception for an invalid result out of one of my algorithms
|
||||
package com.mattrixwv.exceptions;
|
||||
|
||||
|
||||
public class InvalidResult extends Exception{
|
||||
private static final long serialVersionUID = 1L;
|
||||
public InvalidResult(){
|
||||
super();
|
||||
}
|
||||
public InvalidResult(String msg){
|
||||
super(msg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/HexagonalNumberGenerator.java
|
||||
//Matthew Ellison
|
||||
// Created: 08-20-22
|
||||
//Modified: 08-20-22
|
||||
//This class generates hexagonal numbers
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv.generators;
|
||||
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
|
||||
public class HexagonalNumberGenerator implements Iterator<Long>{
|
||||
private Long num;
|
||||
|
||||
public HexagonalNumberGenerator(){
|
||||
num = 1L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext(){
|
||||
return (2 * num * num) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long next(){
|
||||
Long newNum = ((2 * num * num) - num);
|
||||
++num;
|
||||
if(num > 0){
|
||||
return newNum;
|
||||
}
|
||||
else{
|
||||
throw new NoSuchElementException("Number overflow");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isHexagonal(Long x){
|
||||
Long n = Math.round((Math.sqrt(1 + (8 * x)) + 1) / 4);
|
||||
return ((2 * n * n) - n) == x;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//JavaClasses/src/main/java/com/mattrixwv/generators/PentagonalNumberGenerator.java
|
||||
//Mattrixwv
|
||||
// Created: 08-20-22
|
||||
//Modified: 08-20-22
|
||||
//This class generates pentagonal numbers
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv.generators;
|
||||
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
|
||||
public class PentagonalNumberGenerator implements Iterator<Long>{
|
||||
private Long num;
|
||||
|
||||
public PentagonalNumberGenerator(){
|
||||
num = 1L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext(){
|
||||
return (3 * num * num) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long next(){
|
||||
long newNum = ((3 * num * num) - num) / 2;
|
||||
++num;
|
||||
if(num > 0){
|
||||
return newNum;
|
||||
}
|
||||
else{
|
||||
throw new NoSuchElementException("Number overflow");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isPentagonal(Long x){
|
||||
Long n = Math.round((Math.sqrt(1 + (24 * x)) + 1) / 6);
|
||||
return (((3 * n * n) - n) / 2) == x;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenes.java
|
||||
//Matthew Ellison
|
||||
// Created: 06-30-21
|
||||
//Modified: 06-25-22
|
||||
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv.generators;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
|
||||
public class SieveOfEratosthenes implements Iterator<Long>{
|
||||
long possiblePrime;
|
||||
private Map<Long, ArrayList<Long>> dict;
|
||||
|
||||
public SieveOfEratosthenes(){
|
||||
dict = new HashMap<>();
|
||||
possiblePrime = 2;
|
||||
}
|
||||
@Override
|
||||
public boolean hasNext(){
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public Long next(){
|
||||
long prime;
|
||||
|
||||
//If this is the first run just return 2
|
||||
if(possiblePrime <= 2){
|
||||
prime = possiblePrime++;
|
||||
return prime;
|
||||
}
|
||||
|
||||
//Loop until you find a prime number
|
||||
for(;dict.containsKey(possiblePrime);possiblePrime += 2){
|
||||
if(possiblePrime < 0){
|
||||
throw new NoSuchElementException("the next prime cannot be described by a long");
|
||||
}
|
||||
//Create the next entry for all entries in the map
|
||||
for(long num : dict.get(possiblePrime)){
|
||||
if(!dict.containsKey(possiblePrime + num + num)){
|
||||
ArrayList<Long> tempArray = new ArrayList<>(Arrays.asList(num));
|
||||
dict.put(possiblePrime + num + num, tempArray);
|
||||
}
|
||||
else{
|
||||
dict.get(possiblePrime + num + num).add(num);
|
||||
}
|
||||
}
|
||||
//Delete the current entry
|
||||
dict.remove(possiblePrime);
|
||||
}
|
||||
//Save that the number is a prime
|
||||
prime = possiblePrime;
|
||||
//Add the next entry to the prime
|
||||
if(!dict.containsKey(prime * 3)){
|
||||
ArrayList<Long> tempArray = new ArrayList<>(Arrays.asList(prime));
|
||||
dict.put(prime * 3, tempArray);
|
||||
}
|
||||
else{
|
||||
dict.get(prime * 3).add(prime);
|
||||
}
|
||||
//Move on to the next possible prime
|
||||
possiblePrime += 2;
|
||||
|
||||
return prime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
//JavaClasses/src/main/java/mattrixwv/SieveOfEratosthenesBig.java
|
||||
//Matthew Ellison
|
||||
// Created: 06-30-21
|
||||
//Modified: 06-25-22
|
||||
//This class uses to Sieve of Eratosthenes to generate an infinite number of primes
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv.generators;
|
||||
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class SieveOfEratosthenesBig implements Iterator<BigInteger>{
|
||||
BigInteger possiblePrime;
|
||||
private Map<BigInteger, ArrayList<BigInteger>> dict;
|
||||
|
||||
public SieveOfEratosthenesBig(){
|
||||
dict = new HashMap<>();
|
||||
possiblePrime = BigInteger.TWO;
|
||||
}
|
||||
@Override
|
||||
public boolean hasNext(){
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public BigInteger next(){
|
||||
BigInteger prime;
|
||||
|
||||
if(possiblePrime.compareTo(BigInteger.TWO) <= 0){
|
||||
//Return 2 and move to 3
|
||||
prime = possiblePrime;
|
||||
possiblePrime = possiblePrime.add(BigInteger.ONE);
|
||||
return prime;
|
||||
}
|
||||
|
||||
//Loop until you find a prime number
|
||||
for(;dict.containsKey(possiblePrime);possiblePrime = possiblePrime.add(BigInteger.TWO)){
|
||||
//Create the next entry for all entries in the map
|
||||
for(BigInteger num : dict.get(possiblePrime)){
|
||||
BigInteger loc = possiblePrime.add(num).add(num);
|
||||
if(!dict.containsKey(loc)){
|
||||
ArrayList<BigInteger> tempArray = new ArrayList<>(Arrays.asList(num));
|
||||
dict.put(loc, tempArray);
|
||||
}
|
||||
else{
|
||||
dict.get(loc).add(num);
|
||||
}
|
||||
}
|
||||
//Delete the current entry
|
||||
dict.remove(possiblePrime);
|
||||
}
|
||||
//Save that the number is a prime
|
||||
prime = possiblePrime;
|
||||
BigInteger loc = prime.multiply(BigInteger.valueOf(3));
|
||||
if(!dict.containsKey(loc)){
|
||||
ArrayList<BigInteger> tempArray = new ArrayList<>(Arrays.asList(prime));
|
||||
dict.put(loc, tempArray);
|
||||
}
|
||||
else{
|
||||
dict.get(loc).add(prime);
|
||||
}
|
||||
//Move on to the next possible prime
|
||||
possiblePrime = possiblePrime.add(BigInteger.TWO);
|
||||
|
||||
return prime;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//JavaClasses/src/main/java/com/mattrixwv/generators/TriangularNumberGenerator.java
|
||||
//Mattrixwv
|
||||
// Created: 08-20-22
|
||||
//Modified: 08-20-22
|
||||
//This class generates triangular numbers
|
||||
/*
|
||||
Copyright (C) 2022 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
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.mattrixwv.generators;
|
||||
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
|
||||
public class TriangularNumberGenerator implements Iterator<Long>{
|
||||
private Long num;
|
||||
|
||||
public TriangularNumberGenerator(){
|
||||
num = 1L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext(){
|
||||
return (num * num) > 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long next(){
|
||||
Long newNum = ((num * num) + num) / 2;
|
||||
++num;
|
||||
if(num > 0){
|
||||
return newNum;
|
||||
}
|
||||
else{
|
||||
throw new NoSuchElementException("Number overflow");
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isTriangular(Long x){
|
||||
Long n = Math.round((Math.sqrt(1 + (8 * x)) - 1) / 2);
|
||||
return (((n * n) + n) / 2) == x;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user