+ 1

Why am I not getting the sum of prime numbers

I'm using this code to try to get the sum of prime numbers below 2,000,000 but it's not working, please can someone help. https://code.sololearn.com/cBHOYCgSH9JJ/?ref=app

13th Sep 2020, 8:27 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
9 Réponses
+ 2
Where? I added explanation.. Read once..
13th Sep 2020, 9:23 PM
Jayakrishna 🇮🇳
+ 2
Your not printing return value.. And actually, you write x+=sum, initially sum =0 so no harm otherwise your x keep on increase make infinite loop.. but sum =0, it will return. Console.Write(getPrime(20000,0)); you need this. Joseph Oritseweyinmi and also sum range exceeding Integer range.. So use long.. But still by your code now also exceeding long range also... And SoloLearn time limit is less than 4 seconds.. So for long inputs or for infinites, you don't get output...
13th Sep 2020, 9:28 PM
Jayakrishna 🇮🇳
0
Sorry, I don't understand
13th Sep 2020, 9:22 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
0
Why is there no output
13th Sep 2020, 9:24 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
0
Sorry and
13th Sep 2020, 9:32 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
0
It's still not working
13th Sep 2020, 9:33 PM
Joseph Oritseweyinmi
Joseph Oritseweyinmi - avatar
0
Your not modified code for checking for prime... You will get answer with that code, almost n times greater than actual.. You are adding x to sum, for every non-factor value between 2 to x/2... Instead of only for prime. Edit: Joseph Oritseweyinmi Why are you changing function..? The above logic I added is for loop's logic change... If you want make a function for prime check, then use function which you used in your privoius code....
13th Sep 2020, 9:38 PM
Jayakrishna 🇮🇳
0
OK. After your all tries only check this code... This is what I said in first post. public static int getprime(int input,int sum) { for (int x = 2;x <input;x++) { bool prime=true; for(int y =2; y<=x/2; y++) if (x%y == 0) { prime=false; break; } if(prime==true) sum += x; } return sum; } static void Main(string[] args) { Console.Write(getprime(200000, 0)); } // here working upto 65000, after that getting time out. // so try in pc
13th Sep 2020, 10:02 PM
Jayakrishna 🇮🇳
- 1
for (int x = 2;x <= input;x++) { for (int y = 2;y <= x/2;y++) { if (x % y != 0) //by this condition if for ex: x=10,and then for y=3, and 4, x will be added. so instead of just once, adding more times... x += sum; //this shloud be sum+=x; } } And you are not printing return value... Use a function to check prime or not. If prime add else not. If you want go with loop, then Inner loop should be like bool prime=true; for(int y =2; y<=x/2; y++) if (x%y == 0) { prime=false; break; } if(prime==true) sum += x;
13th Sep 2020, 9:13 PM
Jayakrishna 🇮🇳