Skip to content

Instantly share code, notes, and snippets.

@connlark
Last active October 26, 2015 00:46
Show Gist options
  • Save connlark/2b01560f306278175b5a to your computer and use it in GitHub Desktop.
Save connlark/2b01560f306278175b5a to your computer and use it in GitHub Desktop.
/**
* Created by Connor on 10/19/15.
*/
public class Primes {
/** class method called isPrime(int p) which determines if an integer p is a prime number. Assume p > 1. */
public static boolean isPrime(int p) {
if (p <= 1) return false;
if (p == 2) return true;
//check if n is a multiple of 2
if (p%2==0) return false;
//if not, check the odds
for(int i = 3; i * i <= p; i += 2) {
if( p % i == 0)
return false;
}
return true;
}
/** method that prints out the first 100 prime numbers. */
public static void printPrimes(){
int numbersPrinted = 0;
int i = 0;
while (numbersPrinted != 100){
if (isPrime(i)){
System.out.println(i);
numbersPrinted++;
}
i++;
}
}
/* method override for printPrimes() method that prints out the first n prime numbers. */
public static void printPrimes(int n){
int numbersPrinted = 0;
int i = 0;
while (numbersPrinted < n){
if (isPrime(i)){
System.out.println(i);
numbersPrinted++;
}
i++;
}
}
/** method that returns how many prime numbers are less than or equal to the integer max. Note: max could be negative. */
public static int countPrime(int max){
int count = 0;
if (max < 1) return 0;
for (int i = 0; i <= max; i++) {
if (isPrime(i)){
count++;
}
}
return count;
}
/** returns the sum of the first n prime numbers. */
public static int sumPrime(int n) {
if (n < 0) return 0;
int sum = 0;
int primeCount = 0;
int i = 0;
while (primeCount < n){
if (isPrime(i)){
primeCount++;
sum += i;
}
i++;
}
return sum;
}
/** returns the average of the first n prime numbers */
public static double avePrime(int n){
return (double) sumPrime(n) / n;
}
/** returns the maximum “distance” between each pair of consecutive prime numbers <= n. */
public static int primeSpace(int n){
int lastPrime = 0;
int maxDistance = 0;
int newDistance;
for (int i = 0; i <= n; i++) {
if (isPrime(i)){
newDistance = (i - lastPrime);
if (maxDistance < newDistance){
maxDistance = newDistance;
}
lastPrime = i;
}
}
return maxDistance;
}
/** This method returns a String containing the prime factorization of the number n*/
public static String factor(int n){
int temp = n;
String output = "";
boolean found = false;
if (!isPrime(n)) {
while (temp != 1) {
for (int primeNum = 2; !found; primeNum++) {
if (isPrime(primeNum)) {
if (temp % primeNum == 0) {
temp /= primeNum;
output += Integer.toString(primeNum) + "*";
found = true;
}
}
}
found = false;
}
}
else if (n == 1) return output;
else return Integer.toString(n);
int length = output.length();
//format output to not have '*' at the end
return output.substring(0,length-1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment