+ 1
Need help with prime number in C,
I want to creat a prog to count the number of prime numbers in a string. her is my attempt but it doesn't work. https://code.sololearn.com/co7Et39WrL6Q/?ref=app
7 Answers
+ 2
I see how you were using r as your flag for non-primes. Resetting r is fine I changed where it was done and your prime algorithm. You only have to check half the numbers (really less) to determine if it is prime.
https://code.sololearn.com/cn6jp6r7TALO
+ 1
Are you resetting "r=0" on each for loop of i?
https://code.sololearn.com/cQYgROK9ebqs/?ref=app
+ 1
thanks, I like this one but I still don't understand why you add 1 here,
//for(j=2; j<=(tab[i]/2)+1; j++)
+ 1
//Sorry for not getting back to you sooner.
I think it's not necessary to add 1 if we have" <=", then it will be :
//for (j=2;j<=(tab[i]/2);j++) or j<(tab[i]/2)+1 đ€ anyway it's not a big problem, and the code run perfectly.
+ 1
The reason for the +1.
Integer math in C drops any fractions all the below == 1
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
So to ensure we get to half on an odd number we add the +1. When checking for primes its not detrimental not to add the 1.
Hope that clears up the +1.
0
Thank you s.m bro
0
Only have to check up to half of the number, because if they are bigger than half then they cannot be a factor. Example: 24 has 1,2,3,4,6,8 & 12 as factors. 18 has 1,2,3,6 & 9 as factors. No number can have a factor bigger than n/2.
Not sure when it is needed, but the +1 is to ensure the program doesn't round down, eg: 13/2=6 (remember, remainder is ignored when dividing an int).
Did you get Williams code to run correctly? I like his trick to use a comma in the for loop to reset r=0.