Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

What is the 10 001st prime number

This is what I have so far.

 long sum = 0;
 for (long i = 1; i < 104745; i++) {
 if (i % 2 != 0) {
 sum = i;
 }
completion(sum);

That's a great challenge - love the concept.

Checking for non-even is a good start. How about then testing if the number is divisible by three, and every 3+2n divisor after that? (i.e. the next odd number from each even number?) Stop the loop when you have 10,001 results?

Does that make sense?

I'll give this some more thought in the morning - I'm wasting my life watching the election at the moment! Sunderland are being the first, as usual, but that's not going to plan.

Steve.

do iterate through the prime proof algorithm while we've not got to 10,001 identified prime numbers. Increment and repeat ...

Thinking as I type!

2 Answers

Here's my crack at this ...

import java.io.*;
import java.util.Arrays;
import java.util.Date;

public class Prime{
  public static void main(String[] args) {

        int counter = 1;
        boolean prime = true;
        int numerator = 0;
        int denominator = 0;
        float denom = 0.0;

        do {
            numerator++;
            denom = numerator / 2;
            denominator = (int) Math.ceil(denom);
            prime = true;

            for (int i = 2; i <= denominator + 1; i++){
                if(numerator % i == 0){
                    prime = false;
                }
            }
            if(prime){
                counter++;
            }     
        } while(counter < 10001);

     System.out.println(numerator);
     System.out.println(counter);
     }
}

Seems to work OK - it might not be quite right though! It says that the 10,001st prime number is 104,743 which, according to this website is the 10,001st prime number. That's very similar to the number in your for loop so I think your solution was working backwards from the known answer. You counted up to 104,745 which can't be prime as it ends in 5.

Anyway - if you need a walk-through of the code, feel free to ask.

Steve.

Travis Avey
Travis Avey
18,876 Points

Ah yes, the ol' Project Euler problems. I banged my head on this one for a while.. The Sieve of Eratosthenes may point you in the right direction. Best of luck