0

[SOLVED] Prime number recognition

the code is supposed to recognize that the num is prime or not but it is not working for (22,33,... 26,.....) https://code.sololearn.com/cZq5PrtoNybZ/#cpp

3rd Dec 2020, 9:08 PM
athena
athena - avatar
7 Antworten
+ 1
//athena check this code : #include <iostream> using namespace std; int main() { int x,i; cout<<"enter a number.\n"; cin>>x; for(i=2;i<x;i++){ printf("i = %d, %d %c %d == %d\n", i ,x, '%', i, ( x%i) ); if(x%i==0){ cout<<"Not Prime\n"; break; } } if(x == i){ cout<<"Prime\n"; } return 0; }
3rd Dec 2020, 10:55 PM
Jayakrishna 🇮🇳
+ 2
athena The above code can be reduced iterations by taking condition i<=x/2 instead of i<x; And check x/2 == i. Try this as in your own code again.. You're welcome...
4th Dec 2020, 12:04 PM
Jayakrishna 🇮🇳
+ 1
Once revise how if else works... Then try it again.. You have if and else any one those will execute and both have break statement so break get executed in if or in else at 1st iteration so it comes out of loop.. Can't check i=3,...x ever. Instead of x==2, use x%2==0 before loop this will make all even numbers determined by single if block as prime not need to loop.. In loop you can start from 3. and skip even numbers by i=i+2 check only odd numbers.. Remove last else part then try to analyse what is happening next... Edit :athena you did not write x%2==0 but i=2 at 1st iteration in loop..
3rd Dec 2020, 10:36 PM
Jayakrishna 🇮🇳
0
the problem was because of i++ it should have been++i
3rd Dec 2020, 9:15 PM
athena
athena - avatar
0
For any input what your code does is : if x is 2, print prime and breaks, Else x%2==0 : then prints not prime and breaks else print prime breaks loop... It only works i = 2 and not anymore.. What you have to find is : If x%i==0 then print not prime and break loop. Else continue with until i<x.. Out of loop if I ==x means non of i is divided x so it's a prime... Prime has factor only 1 and itself. Ie x%1==0 and x%x==0.. So it has only 2 factor.. Edit : athena break causees comes out of loop.. Nothing with i++ or ++i.
3rd Dec 2020, 9:25 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 but i didn't write an if to analyze x%2==0 at first i declared i as 2 because for x==2 the loop will happen once (i know i can avoid this by changing i<=x to i<x) so i add another if to check if x is equal to 2 or not and if it's not it will check the remainder of x/i and it needed the break because after the dividing it will continue division for other amounts of i so the numbers of cout will be more than once
3rd Dec 2020, 9:35 PM
athena
athena - avatar
0
Jayakrishna🇮🇳 thank you very much ❤️
4th Dec 2020, 9:30 AM
athena
athena - avatar