Added new problems

This commit is contained in:
2022-08-20 16:03:31 -04:00
parent 51447fcbb2
commit a79e60f0fe
22 changed files with 860 additions and 15 deletions

1
files/Problem42Words.txt Normal file

File diff suppressed because one or more lines are too long

View File

@@ -108,7 +108,7 @@
<configuration>
<archive>
<manifest>
<mainClass>mattrixwv.ProjectEuler.Driver</mainClass>
<mainClass>com.mattrixwv.project_euler.Driver</mainClass>
</manifest>
</archive>
<descriptorRefs>

View File

@@ -189,6 +189,6 @@ public class Benchmark{
String timeResults = Stopwatch.getStr(totalTime);
//Tally the results
return "%n%n" + problem.getResult() + "%nIt took an average of " + timeResults + " to run this problem through " + timesRun + " iterations%n%n";
return "\n\n" + problem.getResult() + "\nIt took an average of " + timeResults + " to run this problem through " + timesRun + " iterations\n\n";
}
}

View File

@@ -38,7 +38,8 @@ public class ProblemSelection{
public static final List<Integer> PROBLEM_NUMBERS = new ArrayList<>(Arrays.asList( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 67));
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 67));
//Returns the problem corresponding to the given problem number
public static Problem getProblem(Integer problemNumber){
@@ -82,6 +83,13 @@ public class ProblemSelection{
case 36 : problem = new Problem36(); break;
case 37 : problem = new Problem37(); break;
case 38 : problem = new Problem38(); break;
case 39 : problem = new Problem39(); break;
case 40 : problem = new Problem40(); break;
case 41 : problem = new Problem41(); break;
case 42 : problem = new Problem42(); break;
case 43 : problem = new Problem43(); break;
case 44 : problem = new Problem44(); break;
case 45 : problem = new Problem45(); break;
case 67 : problem = new Problem67(); break;
}
return problem;

View File

@@ -211,7 +211,7 @@ public class Problem11 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("The greatest product of 4 numbers in a line is %d%nThe numbers are %s", ArrayAlgorithms.getProd(greatestProduct), greatestProduct.toString());
return String.format("The greatest product of 4 numbers in a line is %d\nThe numbers are %s", ArrayAlgorithms.getProd(greatestProduct), greatestProduct.toString());
}
//Returns the numbers that were being searched
public List<Integer> getNumbers(){

View File

@@ -292,7 +292,7 @@ public class Problem13 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("The sum of all %d numbers is %d%nThe first 10 digits of the sum of the numbers is %s", nums.size(), sum, (sum.toString()).substring(0, 10));
return String.format("The sum of all %d numbers is %d\nThe first 10 digits of the sum of the numbers is %s", nums.size(), sum, (sum.toString()).substring(0, 10));
}
//Returns the list of 50-digit numbers
public List<BigInteger> getNumbers(){

View File

@@ -85,7 +85,7 @@ public class Problem16 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("%d^%d = %s%nThe sum of the elements is %d", NUM_TO_POWER, POWER, num.toString(), sumOfElements);
return String.format("%d^%d = %s\nThe sum of the elements is %d", NUM_TO_POWER, POWER, num.toString(), sumOfElements);
}
//Returns the number that was calculated
public BigInteger getNumber(){

View File

@@ -86,7 +86,7 @@ public class Problem20 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("%d! = %s%nThe sum of the digits is: %d", TOP_NUM, num.toString(), sum);
return String.format("%d! = %s\nThe sum of the digits is: %d", TOP_NUM, num.toString(), sum);
}
//Returns the number 100!
public BigInteger getNumber(){

View File

@@ -117,9 +117,9 @@ public class Problem21 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
StringBuilder result = new StringBuilder(String.format("All amicable numbers less than %d are%n", LIMIT));
StringBuilder result = new StringBuilder(String.format("All amicable numbers less than %d are\n", LIMIT));
for(int cnt = 0;cnt < amicable.size();++cnt){
result.append(String.format("%d%n", amicable.get(cnt)));
result.append(String.format("%d\n", amicable.get(cnt)));
}
result.append(String.format("The sum of all of these amicable numbers is %d", ArrayAlgorithms.getSum(amicable)));

View File

@@ -81,7 +81,7 @@ public class Problem25 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("The first Fibonacci number with %d digits is %s%nIts index is %d", NUM_DIGITS, number.toString(), index);
return String.format("The first Fibonacci number with %d digits is %s\nIts index is %d", NUM_DIGITS, number.toString(), index);
}
//Returns the Fibonacci number asked for
public BigInteger getNumber(){

View File

@@ -108,7 +108,7 @@ public class Problem26 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("The longest cycle is %d digits long%nIt started with the number %d", longestCycle, longestNumber);
return String.format("The longest cycle is %d digits long\nIt started with the number %d", longestCycle, longestNumber);
}
//Returns the length of the longest cycle
public int getLongestCycle(){

View File

@@ -99,7 +99,7 @@ public class Problem27 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("The greatest number of primes found is %d%nIt was found with A = %d, B = %d%nThe product of A and B is %d", topN, topA, topB, topA * topB);
return String.format("The greatest number of primes found is %d\nIt was found with A = %d, B = %d\nThe product of A and B is %d", topN, topA, topB, topA * topB);
}
//Returns the top A that was generated
public int getTopA(){

View File

@@ -157,7 +157,7 @@ public class Problem32 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("There are %d unique 1-9 pandigitals%nThe sum of the products of these pandigitals is %d", listOfProducts.size(), sumOfPandigitals);
return String.format("There are %d unique 1-9 pandigitals\nThe sum of the products of these pandigitals is %d", listOfProducts.size(), sumOfPandigitals);
}
//Returns the sum of the pandigitals
public long getSumOfPandigitals(){

View File

@@ -0,0 +1,118 @@
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem39.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//If p is the perimeter of a right triangle for which value of p <= 1000 is the number of solutions for the sides {a, b, c} maximized
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
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.project_euler.problems;
import java.util.ArrayList;
import java.util.List;
import com.mattrixwv.Triple;
public class Problem39 extends Problem{
//Variables
//Static variables
private static final long MAX_PERIMETER = 1000;
//Instace variables
private ArrayList<Triple<Long, Long, Long>> longestSolutions;
//Functions
//Constructor
public Problem39(){
super("If p is the perimeter of a right triangle for which value of p <= 1000 is the number of solutions for the sides {a, b, c} maximized");
longestSolutions = new ArrayList<>();
}
//Operational functions
private boolean isRightTriangle(long a, long b, long c){
return (c * c) == ((a * a) + (b * b));
}
//Solve the problem
public void solve(){
//If the problem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Loop for perimeter <= 1000
for(long perimeter = 1;perimeter <= MAX_PERIMETER;++perimeter){
ArrayList<Triple<Long, Long, Long>> solutions = new ArrayList<>();
for(long a = 1;(a * 3) <= perimeter;++a){
for(long b = a;(a + b + b) <= perimeter;++b){
for(long c = b;(a + b + c) <= perimeter;++c){
long sum = a + b + c;
if((isRightTriangle(a, b, c)) && (sum == perimeter)){
solutions.add(new Triple<>(a, b, c));
}
}
}
}
if(solutions.size() >= longestSolutions.size()){
longestSolutions = solutions;
}
}
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
//Reset the problem so it can be run again
@Override
public void reset(){
super.reset();
longestSolutions = new ArrayList<>();
}
//Gets
//Returns a string with the solution to the problem
public String getResult(){
solvedCheck("results");
return String.format("The perimeter with the largest number of solutions is %d", getLongestPerimeter());
}
//Returns the array of solutions
public List<Triple<Long, Long, Long>> getLongestSolutions(){
solvedCheck("array of solutions");
return longestSolutions;
}
//Returns the perimeter of the solution
public long getLongestPerimeter(){
solvedCheck("perimeter");
long perimeter = 0;
if((longestSolutions != null) && (!longestSolutions.isEmpty())){
Triple<Long, Long, Long> solution = longestSolutions.get(0);
perimeter = solution.getA() + solution.getB() + solution.getC();
}
return perimeter;
}
}
/* Results:
The perimeter with the largest number of solutions is 840
It took an average of 6.564 seconds to run this problem through 100 iterations
*/

View File

@@ -0,0 +1,109 @@
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem40.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//An irrational decimal fraction is created by concatenating the positive integers. Find the value of the following expression: d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
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.project_euler.problems;
import java.util.ArrayList;
import com.mattrixwv.ArrayAlgorithms;
public class Problem40 extends Problem{
//Variables
//Static variables
private static final long LARGEST_SUBSCRIPT = 1000000;
//Instance variables
private StringBuilder irrationalDecimal;
private long product;
//Functions
//Constructor
public Problem40(){
super("An irrational decimal fraction is created by concatenating the positive integers. Find the value of the following expression: d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000");
irrationalDecimal = new StringBuilder();
product = 0;
}
//Operational functions
//Solve the problem
public void solve(){
//If the problem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Add numbers to the string until it is long enough
for(Long num = 1L;irrationalDecimal.length() < LARGEST_SUBSCRIPT;++num){
irrationalDecimal.append(num.toString());
}
//Get integers from the string, multiply them, and save the value
ArrayList<Long> nums = new ArrayList<>();
nums.add(Long.valueOf(Character.toString(irrationalDecimal.charAt(0))));
nums.add(Long.valueOf(Character.toString(irrationalDecimal.charAt(9))));
nums.add(Long.valueOf(Character.toString(irrationalDecimal.charAt(99))));
nums.add(Long.valueOf(Character.toString(irrationalDecimal.charAt(999))));
nums.add(Long.valueOf(Character.toString(irrationalDecimal.charAt(9999))));
nums.add(Long.valueOf(Character.toString(irrationalDecimal.charAt(99999))));
nums.add(Long.valueOf(Character.toString(irrationalDecimal.charAt(999999))));
product = ArrayAlgorithms.getLongProd(nums);
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
//Reset the problem so it can be run again
@Override
public void reset(){
super.reset();
irrationalDecimal = new StringBuilder();
product = 0;
}
//Gets
//Returns a string with the solution to the problem
public String getResult(){
solvedCheck("results");
return String.format("The product is %d", product);
}
//Returns the string of the decimal
public String irrationalDecimal(){
solvedCheck("decimal string");
return "0." + irrationalDecimal.toString();
}
//Returns the product of the digits
public long getProduct(){
solvedCheck("product");
return product;
}
}
/* Results:
The product is 210
It took an average of 4.062 milliseconds to run this problem through 100 iterations
*/

View File

@@ -0,0 +1,104 @@
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem41.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//What is the largest n-digit pandigital prime?
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
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.project_euler.problems;
import java.util.ArrayList;
import com.mattrixwv.NumberAlgorithms;
import com.mattrixwv.StringAlgorithms;
public class Problem41 extends Problem{
//Variables
//Instance variables
private long largestPrimePandigital;
//Functions
//Constructor
public Problem41(){
super("What is the largest n-digit pandigital prime?");
largestPrimePandigital = 0;
}
//Operational functions
//Solve the problem
public void solve(){
//If the problem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Get all of the possible numbers that could be pandigital
ArrayList<String> perms = new ArrayList<>();
perms.addAll(StringAlgorithms.getPermutations("1"));
perms.addAll(StringAlgorithms.getPermutations("12"));
perms.addAll(StringAlgorithms.getPermutations("123"));
perms.addAll(StringAlgorithms.getPermutations("1234"));
perms.addAll(StringAlgorithms.getPermutations("12345"));
perms.addAll(StringAlgorithms.getPermutations("123456"));
perms.addAll(StringAlgorithms.getPermutations("1234567"));
perms.addAll(StringAlgorithms.getPermutations("12345678"));
perms.addAll(StringAlgorithms.getPermutations("123456789"));
//Check if the numbers are prime
for(String perm : perms){
long num = Long.parseLong(perm);
if((NumberAlgorithms.isPrime(num)) && (num > largestPrimePandigital)){
largestPrimePandigital = num;
}
}
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
//Reset the problem so it can be run again
@Override
public void reset(){
super.reset();
largestPrimePandigital = 0;
}
//Gets
//Returns a string with the solution to the problem
public String getResult(){
solvedCheck("results");
return String.format("The largest n-digit pandigital prime is %d", largestPrimePandigital);
}
//Returns the largest prime pandigital
public long getLargestPrimePandigital(){
solvedCheck("largest prime pandigital");
return largestPrimePandigital;
}
}
/* Results:
The largest n-digit pandigital prime is 7652413
It took an average of 108.232 milliseconds to run this problem through 100 iterations
*/

View File

@@ -0,0 +1,151 @@
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem42.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//Triangular number t(n) = (n * (n + 1)) / 2. For A = 1, B = 2, ... find the number of triangular words in the file
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
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.project_euler.problems;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class Problem42 extends Problem{
//Variables
//Static variables
private static final String FILE_NAME = "files/Problem42Words.txt";
private static final ArrayList<String> fileWords = new ArrayList<>();
//Instance variables
private ArrayList<String> triangleWords;
//Functions
//Constructor
public Problem42(){
super("Triangular number t(n) - (n * (n + 1)) / 2. For A = 1, B = 2, ... find the number of trinagular words in the file");
triangleWords = new ArrayList<>();
}
//Operational function
//Read words from file into array
private void readFile(){
if(!fileWords.isEmpty()){
return;
}
File file = new File(FILE_NAME);
if(file.exists()){
try{
List<String> lines = Files.readAllLines(file.toPath());
for(String line : lines){
String[] words = line.split(",");
for(String word : words){
fileWords.add(word.replace("\"", ""));
}
}
}
catch(IOException error){
throw new RuntimeException(error);
}
}
else{
throw new RuntimeException("File not found");
}
}
//Tet the sum of all letters in the string passed in
private long getValueFromWord(String word){
long sum = 0;
for(char ch : word.toUpperCase().toCharArray()){
long val = ch - 'A' + 1;
sum += val;
}
return sum;
}
//Check if the number passed in is a triangular number
private boolean isTriangularNumber(long num){
long counter = 1;
long triangularNumber = 0;
while(triangularNumber < num){
triangularNumber += counter++;
if(triangularNumber == num){
return true;
}
}
return false;
}
//Solve the problem
public void solve(){
//If the problem has already been solved do nothign and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Read the file into the array
readFile();
//Run through all elements in the array checking for triangular words
for(String word : fileWords){
long value = getValueFromWord(word);
if(isTriangularNumber(value)){
triangleWords.add(word);
}
}
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
//Reset the problem so it can be run again
@Override
public void reset(){
super.reset();
triangleWords = new ArrayList<>();
}
//Gets
//Returns a string with the solution to the porblem
public String getResult(){
solvedCheck("results");
return String.format("The number of triangular numbers is %d", getNumberTriangularNumbers());
}
//Returns the triangular words
public List<String> getTriangularWords(){
solvedCheck("triangular words");
@SuppressWarnings("unchecked")
ArrayList<String> clone = (ArrayList<String>)triangleWords.clone();
return clone;
}
//Returns the number of triangular words
public int getNumberTriangularNumbers(){
solvedCheck("number of triangular words");
return triangleWords.size();
}
}
/* Results:
The number of triangular numbers is 162
It took an average of 166.881 microseconds to run this problem through 100 iterations
*/

View File

@@ -0,0 +1,113 @@
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem43.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//Find the sum of all 0-9 pandigital numbers with this property
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
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.project_euler.problems;
import java.util.ArrayList;
import java.util.List;
import com.mattrixwv.ArrayAlgorithms;
import com.mattrixwv.NumberAlgorithms;
import com.mattrixwv.StringAlgorithms;
public class Problem43 extends Problem{
//Variables
//Instance variables
private ArrayList<Long> subPrimePandigitals;
//Functions
//Constructor
public Problem43(){
super("Find the sum of all 0-9 pandigital numbers with this property");
subPrimePandigitals = new ArrayList<>();
}
//Operational functions
//Solve the problem
public void solve(){
//If the porblem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Get all of the 0-9 pandigitals
List<String> pandigitals = StringAlgorithms.getPermutations("0123456789");
//Get all of the primes we need
List<Long> primes = NumberAlgorithms.getNumPrimes(7L);
//Break them into their component parts and see if they are divisible by the prime numbers
for(String pandigital : pandigitals){
boolean foundPrime = true;
for(int cnt = 3;cnt < pandigital.length();++cnt){
String subNum = pandigital.substring(cnt - 2, cnt + 1);
long num = Long.parseLong(subNum);
if((num % primes.get(cnt - 3)) != 0){
foundPrime = false;
break;
}
}
if(foundPrime){
Long num = Long.parseLong(pandigital);
subPrimePandigitals.add(num);
}
}
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
//Reset the problem so it can be run again
@Override
public void reset(){
super.reset();
subPrimePandigitals = new ArrayList<>();
}
//Gets
//Returns a string with the solution to the problem
public String getResult(){
solvedCheck("results");
return String.format("The sum of all pandigitals with the property is %d", getSumSubPrimePandigitals());
}
//Returns the list of sub-prime Pandigitals
public List<Long> getSubPrimePandigitals(){
solvedCheck("sub prime pandigitals");
return subPrimePandigitals;
}
//Returns the sum of the list of sub-prime pandigitals
public long getSumSubPrimePandigitals(){
solvedCheck("sum of sub prime pandigitals");
return ArrayAlgorithms.getLongSum(subPrimePandigitals);
}
}
/* Results:
The sum of all pandigitals with the property is 16695334890
It took an average of 1.008 seconds to run this problem through 100 iterations
*/

View File

@@ -0,0 +1,119 @@
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem44.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//Pentagonal number P = ((n * (3 * n - 1)) / 2). Find 2 pentagonal numbers whos sum and difference are also pentagonal numbers
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
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.project_euler.problems;
import java.util.ArrayList;
import java.util.List;
import com.mattrixwv.generators.PentagonalNumberGenerator;
public class Problem44 extends Problem{
//Variables
//Instance variables
private PentagonalNumberGenerator generator;
private List<Long> pentagonalList;
private long pentagonalNumber1;
private long pentagonalNumber2;
//Functions
//Constructor
public Problem44(){
super("Find 2 pentagonal numbers whos sum and difference are also pentagonal numbers");
generator = new PentagonalNumberGenerator();
pentagonalList = new ArrayList<>();
pentagonalNumber1 = 0;
pentagonalNumber2 = 0;
}
//Operational functions
//Solve the porblem
public void solve(){
//If the porblem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Keep generating pentagonal numbers and checking if their sum and difference is also pentagonal
while(pentagonalNumber1 == 0){
//Generate a new number and check it against every element we have already generated
Long newNum = generator.next();
//Go through every number in the list and check if their sum and difference are pentagonal
for(Long num : pentagonalList){
if(PentagonalNumberGenerator.isPentagonal(newNum + num) && PentagonalNumberGenerator.isPentagonal(newNum - num)){
pentagonalNumber1 = num;
pentagonalNumber2 = newNum;
break;
}
}
pentagonalList.add(newNum);
}
//Stop the timer
timer.stop();
//Set a flag to show the porblem is solved
solved = true;
}
//Reset the porblem so it can be run again
@Override
public void reset(){
super.reset();
generator = new PentagonalNumberGenerator();
pentagonalList = new ArrayList<>();
pentagonalNumber1 = 0;
pentagonalNumber2 = 0;
}
//Gets
//Returns a string with the solution to the problem
public String getResult(){
solvedCheck("results");
return String.format("The difference of the pentagonal numbers is %d", Math.abs(pentagonalNumber1 - pentagonalNumber2));
}
//Returns the list of pentagaonl numbers
public List<Long> getPentagonalList(){
solvedCheck("pentagonal list");
return new ArrayList<>(pentagonalList);
}
//Returns the first pentagonal number
public long getPentagonalNumber1(){
solvedCheck("first pentagonal number");
return pentagonalNumber1;
}
//Returns the second pentagonal number
public long getPentagonalNumber2(){
solvedCheck("second pentagonal number");
return pentagonalNumber2;
}
}
/* Results:
The difference of the pentagonal numbers is 5482660
It took an average of 23.359 milliseconds to run this problem through 100 iterations
*/

View File

@@ -0,0 +1,122 @@
//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem45.java
//Mattrixwv
// Created: 08-20-22
//Modified: 08-20-22
//If p is the perimeter of a right triangle for which value of p <= 1000 is the number of solutions for the sides {a, b, c} maximized
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
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.project_euler.problems;
import com.mattrixwv.generators.HexagonalNumberGenerator;
import com.mattrixwv.generators.PentagonalNumberGenerator;
import com.mattrixwv.generators.TriangularNumberGenerator;
public class Problem45 extends Problem{
//Variables
//Static variables
private static final long MIN_NUMBER = 40756;
//Instance variables
private long num;
private TriangularNumberGenerator triGen;
private PentagonalNumberGenerator penGen;
private HexagonalNumberGenerator hexGen;
//Functions
//Constructor
public Problem45(){
super("Find the next triangle number after 40755 that is also pentagonal and hexagonal");
num = 0;
triGen = new TriangularNumberGenerator();
penGen = new PentagonalNumberGenerator();
hexGen = new HexagonalNumberGenerator();
}
//Operational functions
//Solve the problem
public void solve(){
//If the porblem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Generate the next number after MIN_NUMBER
long triNum = 0;
while(triNum < MIN_NUMBER){
triNum = triGen.next();
}
long penNum = 0;
while(penNum < MIN_NUMBER){
penNum = penGen.next();
}
long hexNum = 0;
while(hexNum < MIN_NUMBER){
hexNum = hexGen.next();
}
//Generate the next numbers until they all match
boolean matchFound = false;
while(!matchFound){
hexNum = hexGen.next();
while(penNum < hexNum){
penNum = penGen.next();
}
while(triNum < hexNum){
triNum = triGen.next();
}
if((hexNum == penNum) && (hexNum == triNum)){
num = hexNum;
matchFound = true;
}
}
//Stop the timer
timer.stop();
//Throw a flag to show the problem is solved
solved = true;
}
//Reset the porblem so it can be run again
@Override
public void reset(){
super.reset();
num = 0;
triGen = new TriangularNumberGenerator();
penGen = new PentagonalNumberGenerator();
hexGen = new HexagonalNumberGenerator();
}
//Gets
//Returns a string with the solution to the problem
public String getResult(){
solvedCheck("results");
return String.format("The next triangular/pentagonal/hexagonal number is %d", num);
}
//Returns the number
public long getNum(){
solvedCheck("triangular/pentagonal/hexagonal number");
return num;
}
}
/* Results:
The next triangular/pentagonal/hexagonal number is 1533776805
It took an average of 589.688 microseconds to run this problem through 100 iterations
*/

View File

@@ -104,7 +104,7 @@ public class Problem8 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("The greatest product is %d%nThe numbers are %s", maxProduct, maxNums);
return String.format("The greatest product is %d\nThe numbers are %s", maxProduct, maxNums);
}
//Returns the string of numbers that produces the largest product
public String getLargestNums(){

View File

@@ -104,7 +104,7 @@ public class Problem9 extends Problem{
@Override
public String getResult(){
solvedCheck("result");
return String.format("The Pythagorean triplet is %d + %d + %d%nThe numbers' product is %d", a, b, Math.round(c), a * b * Math.round(c));
return String.format("The Pythagorean triplet is %d + %d + %d\nThe numbers' product is %d", a, b, Math.round(c), a * b * Math.round(c));
}
//Returns the length of the first side
public int getSideA(){