Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- public class Prime {
- public int current = 0;
- public int nextPrime() {
- while (!Prime.isPrime(++this.current)) {
- }
- return this.current;
- }
- public static double sumOfPrimesBelowN(int n) {
- Prime p = new Prime();
- double total = 0;
- double current = p.nextPrime();
- while (current < n) {
- total += current;
- current = p.nextPrime();
- }
- return total;
- }
- public static Integer[] primesBelow(int i) {
- List<Integer> primes = new ArrayList<Integer>();
- Prime p = new Prime();
- double current = p.nextPrime();
- while (current < i) {
- primes.add((int) current);
- current = p.nextPrime();
- }
- return primes.toArray(new Integer[primes.size()]);
- }
- public static double largestPrimeFactor(double n) {
- Prime p = new Prime();
- double largest = 0;
- double current = p.nextPrime();
- while (current <= n) {
- if (n % current == 0) {
- n /= current;
- if (current > largest) {
- largest = current;
- }
- }
- current = p.nextPrime();
- }
- return largest;
- }
- public static double nthPrime(int i) {
- int counter = 1;
- Prime p = new Prime();
- double current = p.nextPrime();
- while (counter < i) {
- current = p.nextPrime();
- counter++;
- }
- return current;
- }
- public static double largestPrimeUnder(int i) {
- Prime p = new Prime();
- double largest = 0;
- double current = p.nextPrime();
- while (current < i) {
- if (current > largest) {
- largest = current;
- current = p.nextPrime();
- }
- }
- return largest;
- }
- public static boolean isPrime (int n) {
- if (n <= 1) {
- return false;
- } else if (n == 2) {
- return true;
- } else if (n % 2 == 0) {
- return false;
- }
- for (int i = 3; i <= Math.sqrt(n); i+=2) {
- if (n % i == 0)
- return false;
- }
- return true;
- }
- }
Add Comment
Please, Sign In to add comment