c# - Sum of primes for large numbers -
i've been working on problem time , can't figure out why keep getting overflow error.
the code works fine point doesn't work larger values. have tested , found the breaking point input 225287 (with last non-breaking value being 225286, gives output of 2147431335).
how can work 2,000,000?
class sumofprimes{ static void main(string[] args) { primes primes = new primes(2000000); console.writeline(primes.list_of_primes.sum()); console.readline(); } } class primes { public hashset<int> all_numbers = new hashset<int>(); public hashset<int> list_of_primes = new hashset<int>(); public hashset<int> list_of_nonprimes = new hashset<int>(); public primes(int n) { all_numbers = new hashset<int>(enumerable.range(1, n)); (int = 2; < math.sqrt(n) + 1; i++) { (int j = 3; j <= n / i; j++) list_of_nonprimes.add(i * j); } list_of_primes = new hashset<int>(all_numbers.except(list_of_nonprimes)); } }
the values have doesn't fit in memory size of int, try using biginteger used on website here.
http://msdn.microsoft.com/en-us/library/system.numerics.biginteger.aspx
Comments
Post a Comment