Functions: Prime

Hi I'm writing a program with two functions: int getNumberFromUser() that asks user for input and ensures the number is >2 and bool isPrime(int n) that returns true if n is prime. The objective is to find all prime numbers up till a certain number so if the user-chosen number was 11, the program should display 2,3,5,7,11. I'm getting some errors. Can someone help me out?

#include <iostream>
using namespace std;

int getNumberFromUser();
bool isPrime();

int num;
bool prime;

int main()
{
getNumberFromUser();
isPrime();
return 0;
}


int getNumberFromUser()
{
cout << "Please enter a positive integer\n";
cin >> num;
}

bool isPrime(int n)
{
for(int i=2; i<=num; i++)
{
prime=true;
for(int n=2; n<=(i-1); n++)
{
if(i%n==0)
{
prime = false;
}
}
if(prime)
{
cout << i << " is prime\n";
}
}
}
firstly as u say in ur question u r ensuring that number must be greater then 2 ... but u havnt type any condition for it
after recieving number from user .... where are u using it???? u havnt return it!!! and ur function isPrime(int n) have one parameter so in main type isPrime( getNumberFromUser() );
and in getNumberFromUser() type return num;
@Meera Kumar

Please place your code in [dode][/code] tags. Also please supply (exact) errors if you don't understand what they mean.

In your isPrime function definition after the main function, you have an argument which is not present in your function prototype or the call from main.

@noorali15

Please don't use shortened "words" such as 'r' or 'u'. It's really hard to read.
This is a better function for prime evaluation:

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
#include <cmath>
bool isPrime (int num)
{
    if (num <=1)
        return false;
    else if (num == 2)         
        return true;
    else if (num % 2 == 0)
        return false;
    else
    {
        bool prime = true;
        int divisor = 3;
        double num_d = static_cast<double>(num);
        int upperLimit = static_cast<int>(sqrt(num_d) +1);
        
        while (divisor <= upperLimit)
        {
            if (num % divisor == 0)
                prime = false;
            divisor +=2;
        }
        return prime;
    }
}


Now just loop it to evaluate if all numbers up to the number input by the user are prime or not, and std::cout if the value is prime.
Last edited on
Topic archived. No new replies allowed.