C/C++ prime number discriminator

Asked 2 years ago, Updated 2 years ago, 81 views

#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

2022-09-20 19:50

1 Answers

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 << ", ";
    }
}


2022-09-20 19:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.