c# - Find prime using square root -
here question,
find sum of primes below 2 million.
my code lists many non-primes such 9,15..., wrong?
using system; using system.collections.generic; using system.diagnostics; using system.linq; using system.text; using system.threading.tasks; namespace p10 { // sum of primes below 10 2 + 3 + 5 + 7 = 17. find sum of primes below 2 million. class program { static list<long> list = new list<long>(); static void main(string[] args) { stopwatch sw = stopwatch.startnew(); list.add(2); list.add(3); long x = list.last(); while (x < 2000000) { x += 2; findprime(x); } long y = list.sum() - list.last(); console.writeline(y); console.writeline("time used (float): {0} ms", sw.elapsed.totalmilliseconds); console.writeline("time used (rounded): {0} ms", sw.elapsedmilliseconds); console.readkey(); } static void findprime(int64 p) { int64 max = (int64)math.ceiling(math.sqrt(p)); foreach (long n in list) { while (n <= max) { if (p / n == 0) { continue; } else { list.add(p); break; } }break; } } } }
when testing if 1 number divisible another, want know if remainder zero. change this:
if (p / n == 0)
to this:
if (p % n == 0)
but still looks there issues loop. can rewrite as:
static void findprime(long p) { long max = (long)math.ceiling(math.sqrt(p)); foreach (long n in list) { if (n > max) { break; } else if (p % n == 0) { return; } } list.add(p); }
Comments
Post a Comment