Prime numbers in C++. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Prime numbers in C++.

I was trying to code prime numbers in C++, but my code isnt working as expected. Can anyone please send me the correct code(with telling what were my errors in the code) #include <iostream> using namespace std; int main() { for (int x=0;x<26;x++){ int f=0; for (int y=2;y<=x;y++){ if (x%y==0){ cout<<x<<" is not a prime no."<<endl; f=1; break; } if (f==0){ cout<<x<<" is a prime no."<<endl; } } } return 0; }

20th Sep 2021, 3:48 AM
Aryan Silswal
Aryan Silswal - avatar
2 Answers
+ 3
1) the statament "if ( f == 0 )" should be outside the second for loop. 2) you don't need to evaluate all the way to "x" to confirm if the number is prime or not, one way is to only check till half of the number (or square root of that number for even less iterations ) https://code.sololearn.com/cGyh4EjrJGD0/?ref=app
20th Sep 2021, 3:52 AM
Arsenic
Arsenic - avatar
+ 2
Working!! Thanks a lot.
20th Sep 2021, 4:21 AM
Aryan Silswal
Aryan Silswal - avatar