help :(

can anyone plz help me with this :/
i have to write a program that prompts the user to enter two positive integers m and n where m < n then
output all prime numbers in the range m and n, inclusive. You must write a function that would test
a number whether it is prime.

i wrote the codes but every time i enter two integers it gives me the numbers between those two integers and i dont know i what i did wrong. plz help
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  # include <iostream>

using namespace std;

bool isPrime(int number);

int main()
{
    int m;
    int n;
    int number;

    cout << "Enter two integers m and n, m < n:";
    cin >> m;
    cin >> n;
    cout << endl;
    cout << " The primes between " << m << " and " << n << " are: ";
    for (int i = m; i <= n; i++ )
    {
        if (isPrime(i))
            cout << " "<< i << " ";
    }
    return 0;
}
bool isPrime(int number)
{

    for (int i=2; i<number; i++)
        if (number % i == 0)
            return false;
        else
            return true;


}
The code in your loop is wrong.
1
2
3
4
5
    for (int i=2; i<number; i++)
        if (number % i == 0)
            return false;
        else
            return true;

If your number is not evenly divisible by i, the function immediately returns true. So for odd numbers which are not prime, the function will return true the first time the loop runs and i == 2.

What it should look like is this:
1
2
3
4
5
6
7
8
9
10
11
bool isPrime(int number)
{

    for (int i=2; i<number; i++)
    {
        if (number % i == 0)
            return false;
    }

    return true;
}

by placing the return true statement after the loop, you ensure that the function will not return true unless none of the numbers tested can evenly divide the input.
Last edited on
# include <iostream>

using namespace std;


int main()
{
int m;
int n;
int number;

cout << "Enter two integers m and n, m < n:"<<endl;
cout<< "Enter m: ";
cin >> m;
cout<< "Enter n: ";
cin >> n;
cout << endl;
cout << " The primes between " << m << " and " << n << " are: ";
for (int i = m; i <= n; i++ )
{
if ((i==2||i==3||i==5||i==7)||(!(i%2==0||i%3==0||i%5==0||i%7==0)))
cout << " "<< i << " ";
}

return 0;
}
thnk uuuuu soooo mucccchhhhhh :D im happy now :D
Layanm:

Start first:

if it can be modulated by 2, then it's not prime. Next from 3, to (int(number) / 2) check if it can be modulated. that's the most efficient method.
Topic archived. No new replies allowed.