#include <iostream>
using namespace std;
int main(){
int begin, end, i;
int condition = 0;
cout << "Enter two integers between range 1 to 100" <<endl;
cin >> begin >> end;
while(begin <0 || end > 100)
{
cout << "Enter two integers again please" << endl;
cin >> begin >> end;
}
for ( i = begin; i <= end; i++ ) {
for (int j = 2; j <= i/2; j++ ) {
if (i % j == 0) {
condition= 1;
break;
}
else {
break;
}
}
if (condition)
cout << "The number " << i << " is not prime number" << endl;
else
cout << "The number " << i << " is prime number" << endl; } }
When creating a decimal discriminator program, people use the conditional expression (int j = 2; j <= i/2; j++) in the second iteration, so why use the condition j <=i/2? And what's the reason for this program to print out that it's not even a prime number?
c c++ primes
There are many ways to get the prime number.
Like the code above, there is also a way to determine the prime number by dividing a number from 2.
In this way, when you say x, you only need to check from 2 to the root (x). It's a mathematical content, so it's hard for me to explain why I have to go that far.
So originally, you can check from 2 to the root (x), but the above code is checked from x/2 because it is cumbersome to find the root. Since x/2 is a little bit larger than the root (x), there's no problem finding the prime number.
Looking at the code, there are some problems.
Please refer to the code below.
#include <iostream>
using namespace std;
int main() {
int begin, end;
int condition = 0;
cout << "Enter two integers between range 1 to 100" << endl;
cin >> begin >> end;
while (begin < 0 || end > 100)
{
cout << "Enter two integers again please" << endl;
cin >> begin >> end;
}
for (int i = begin; i <= end; i++) {
condition = 0;
if (i == 1)
condition = 1;
for (int j = 2; j <= (i / 2); j++) {
if (i % j == 0) {
condition = 1;
break;
}
}
/*
if (condition)
cout << "The number " << i << " is not prime number" << endl;
else
cout << "The number " << i << " is prime number" << endl;
*/
if (condition == 0)
cout << i << ", ";
}
}
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
618 Uncaught (inpromise) Error on Electron: An object could not be cloned
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
578 Understanding How to Configure Google API Key
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.