Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:15
Show Gist options
  • Save dmnugent80/7ff8a3a96b4a0186bd70 to your computer and use it in GitHub Desktop.
Save dmnugent80/7ff8a3a96b4a0186bd70 to your computer and use it in GitHub Desktop.
Nth Prime Number and Sum of Primes
public class NthPrime
{
public static void main(String[] args)
{
int curr = 0;
int count = 1;
for (int i = 3; count < 10001; i+=2){
if (isPrime(i)){
count++;
curr = i;
}
}
System.out.print("10001th prime: " + curr);
}
public static boolean isPrime(int n) {
if (n == 2) return true;
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
}
//output:
//10001th prime: 104743
//To optimize, use:
//http://www.algolist.net/Algorithms/Number_theoretic/Sieve_of_Eratosthenes
public class SumOfPrimes
{
public static void main(String[] args)
{
long sum = 2;
for (long i = 3; i < 2000000; i+=2){
if (isPrime(i)){
sum += i;
}
}
System.out.print("sum of primes under 2 million: " + sum);
}
public static boolean isPrime(long n) {
if (n == 2) return true;
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
}
/*output:
sum of primes under 2 million: 142913828922
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment