Files
ProjectEulerJava/src/main/java/com/mattrixwv/project_euler/problems/Problem7.java
2023-06-30 21:59:11 -04:00

93 lines
2.5 KiB
Java

//ProjectEulerJava/src/main/java/mattrixwv/ProjectEuler/Problems/Problem7.java
//Matthew Ellison
// Created: 03-01-19
//Modified: 06-27-23
//What is the 10001th prime number?
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
/*
Copyright (C) 2023 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.NumberAlgorithms;
public class Problem7 extends Problem{
//Variables
//Static variables
private static final long NUMBER_OF_PRIMES = 10001; //The number of primes we are trying to get
//Instance variables
protected List<Long> primes;
//Functions
//Constructor
public Problem7(){
super(String.format("What is the %dth prime number?", NUMBER_OF_PRIMES));
primes = new ArrayList<>();
}
//Operational functions
//Solve the problem
@Override
public void solve(){
//If the problem has already been solved do nothing and end the function
if(solved){
return;
}
//Start the timer
timer.start();
//Setup the variables
primes = NumberAlgorithms.getNumPrimes(NUMBER_OF_PRIMES); //Holds the prime numbers
//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();
primes.clear();
}
//Gets
//Returns the result of solving the problem
@Override
public String getResult(){
solvedCheck("result");
return String.format("The %dth prime number is %d", NUMBER_OF_PRIMES, primes.get(primes.size() - 1));
}
//Returns the requested prime number
public long getPrime(){
solvedCheck("prime");
return primes.get(primes.size() - 1);
}
}
/* Results:
The 10001th prime number is 104743
It took an average of 27.343 milliseconds to run this problem through 100 iterations
*/