All Prime Numbers in interval [2,n]

Hello everyone,

My goal is to make a program that asks the user to input a positive integer n that is greater than 1. The program is then supposed to display all the prime numbers in the interval [2,n].

I came up with the following code. It doesn't work, as nothing is outputted after entering an integer.

My strategy was to make a function called 'Prime' that returns a 1 if it is not prime, and a 7 if it is prime. I then use this function in Main.

What I am I doing wrong? I would appreciate feedback.

Thanks in advance!



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
36
37
#include <iostream>
using namespace std;

int Prime(int x);

int main()
{
    cout << "Input a positive integer greater than 1." << endl;
    int n,i;
    cin >> n; 
  
    for(i=2;i<=n;++i)
    {
        if(Prime(i)==7)
        {
        cout << i << endl; 
        }
        break;
    }
return 0;
}

int Prime(int x)
{
    int a;
    for (a=2;a<x;++a)
    {
        if(x%a==0)
        {
            return 1; 
        }
        else
        {
            return 7;
        }
    }
}
Last edited on
The loop at line 26 never completes.
On the very first iteration it will either return 1 or it will return 7.

For a number to be "not prime" it is sufficient to find that there is a single factor.
But for a number to be prime, it is necessary to test more than a single factor, it is necessary to test all possible divisors (or some optimised version) and show that none of them are factors.
Thank you!
Topic archived. No new replies allowed.