1
   public static void algorithmOne(int n){

      long startTime = System.currentTimeMillis();

      search:
      for (int possiblePrime = 2; possiblePrime <= n; possiblePrime++){

         for (int divisor = 2; divisor < possiblePrime; divisor++)
            if ( possiblePrime%divisor == 0 && possiblePrime != divisor )
               continue search;

         System.out.println(possiblePrime);
      }
      long endTime = System.currentTimeMillis();
      System.err.println(endTime - startTime);
   }

This is a method to find prime numbers I cant work out why i don't reach the "System.err.println(endTime - startTime);" line.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
bob
  • 29
  • 1
  • 4

2 Answers2

1

I would guess that you are reaching your time difference println(), but you're not seeing it where you expect. This is because you're printing it to stderr - so you're not guaranteed it gets appended after all of the println()'s to standard output.

Try printing to stdout instead...

As for your algorithm for primality testing - have a look at these two questions about deciding primality (there are links there). Also this discusses finding prime factors, which is not the same problem but has some insights you might be interested in. Specifically, consider the following:

  • Your inner loop only needs to go up to sqrt(n), as if a is a factor of n, then so is n/a.
  • All prime factors after 3 are of the form 6n-1 or 6n+1 (think about it), so you can loop over . If you think of the Sieve of Erathostenes you can think of additional such 'dirty' optimizations.

That's "easy stuff", there's a lot more you could do. But, really, why should you even write a primality test yourself? There is existing code you could use.

Community
  • 1
  • 1
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • eek :( I posted algorithm one instead of number two which was the one that had the problem. but any how I had System.out.err(endTime - startTime); instead of System.err.println(endTime - startTime) The program still compiled so ive been having issues with another issue that wass all cause by this... – bob Apr 07 '13 at 05:42
  • @bob: I still recommend that you read up a bit on primality testing, it's quite interesting. – einpoklum Apr 07 '13 at 05:47
1

Try this out :

    long startTime = System.nanoTime();

    search: for (int possiblePrime = 2; possiblePrime <= 10; possiblePrime++) {

        for (int divisor = 2; divisor < possiblePrime; divisor++)
            if (possiblePrime % divisor == 0 && possiblePrime != divisor)
                continue search;

        System.out.println(possiblePrime);
    }
    long endTime = System.nanoTime();
    System.out.println(startTime);
    System.out.println(endTime);
    System.out.println("Total time taken is : " + (endTime - startTime));
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38