Prime generating number finder not producing correct output

随声附和 提交于 2019-12-03 21:59:31

The maths of your sieve looks fine to me. I hacked it around to use a BitSet which is much more space efficient. Is 5761455 primes below 100,000,000 correct?

Once I got your code working I got the same figure you get (12094504411075) what figure should you be getting?

I think this bit is wrong (I have changed the variable names to match the question for clarity)

    for(int d = 2; d < Math.sqrt(n+3); d++) {
      if (n % d == 0) {
        numDivisors++;
        int check = d + n / d;
        if (primes.get(check)) {
          // **** What does done mean??? ****
          //done = true;
          numPrimeChecks++;
        } else {
          // **** Added! Got a divisor that did not check. No point in going on.
          break;
        }
      } else {
        // **** Why break here??? ****
        //break;
      }

    }

NB I have edited this code to reflect what we finally decided was a correct solution.

Why are you breaking out of the d loop as soon as you hit a d that does not divide n? Surely that cannot be right.

However, I think you can break out of the d loop when you have a divisor that does not check.

Also, what is your intended functionality of done? It seems to have no real function.

And, why do you start sum at 3?

Removing the break I now get the value 1739023853139. Is this correct?

Added

Here's my sieve. Identical to yours but builds a BitSet which is a much more efficient structure than a HashSet in this case:

public static BitSet sieveOfEratosthenes(int n) {
  BitSet isPrime = new BitSet(n);

  // Iniially all numbers are prime.
  for (int i = 2; i <= n; i++) {
    isPrime.set(i);
  }

  // mark non-primes <= N using Sieve of Eratosthenes
  for (int i = 2; i * i <= n; i++) {

    // if i is prime, then mark multiples of i as nonprime
    // suffices to consider mutiples i, i+1, ..., N/i
    if (isPrime.get(i)) {
      for (int j = i; i * j <= n; j++) {
          isPrime.clear(i * j);
      }
    }

  }

  //System.out.println("Found " + isPrime.cardinality() + " primes");
  return isPrime;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!