+ 2
Why it prints one step more? [Solved]
I made this simple C++ program to print prime numbers up to a number entered by the user but it prints one prime number more than the number entered. I can't figure out why it is doing so! Please help, https://www.sololearn.com/compiler-playground/cE7KoW71k7J8/#cpp
2 ответов
+ 2
Working link in app version :
https://code.sololearn.com/cE7KoW71k7J8/#cpp
edit:
Sarthak Gupta
you code have some logic flaw..
it is because in inner while loop, you are incrementing num upto a next prime number..
so for example if input is 10 then 7 is prime .
it goes again into loop when 7<10 but exit inner loop when num=11 , it printed then goes to check outer loop condition 12<10 false.
if you enter a prime number then it won't print one more prime number.
but it fails some cases :
see 31 is prime
when I=2, next 32%2==0 then next num = 33,
when i=3, 33%3=0 then num = 34,
when i=17, 34%17=0 so i=17 , and next number is num=35.
now but there no factors exist between i=18 to 34.
num<i => 35<35 breaks loop. causing 35 is prime number. your logic is not checking 5,7 factors for 35.
reset I=2 when increment num;
and print num if it is within limit.
hope it helps..
+ 1
@Jayakrishna🇮🇳 Thank you so much, I understood the flaw and now it is working perfectly.