Prime Number Finder

I am attempting to write code that receives a number from the user and outputs the largest prime number underneath the user's number. There are no errors in my code, but no matter what number is imputed, the program says the largest prime number is 1. I cannot find where the issue is in the code. Here is the code I wrote:

#include <cstdlib>
#include <iostream>
#include <cmath>

using namespace std;

bool isPrime(int num);//function prototype

int main()
{
int num;
cout<<"Enter a whole number greater than 2."<<endl;
cin>>num;

bool Done(0);
int i;
for(i=num; i>0; i=i-1)
{
if( isPrime(i) && Done==0)
{
cout<<i<<" is the highest prime number under your number."<<endl;
Done=1;
}
}

system("PAUSE");
return EXIT_SUCCESS;
}

bool isPrime(int num)
{
int i, r;
bool prime (1);
for (i=2; i<= num; i++)
{
r=num%i;
if(r==0)
{
prime = 0;
}
}
return prime;
}
Last edited on
You end up moduling the number your checking by itself on the last iteration of the loop in the isPrime function. That will always have a remainder of zero, and it will give you a false negative.

Once you realize a number isn't prime, you should also break out of the loop checking.
I made some changes, vut I don't know if it will work or not. Good luck!
Code:
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
38
39
40
#include <cstdlib>
#include <iostream>
using namespace std;
bool isPrime(int num);//function prototype
int main()
{
double restart;
while(restart!=2){
int num;
cout<<"Enter a whole number greater than 2."<<endl;
cin>>num;
if(num>2){
for(int i=num;i>0;i--){
bool Done(0);
if( isPrime(i) && Done==0){
cout<<i<<" is the highest prime number under your number."<<endl;
Done=1;}}
system("PAUSE");
cout<<"Restart?\n1) Yes\n2) No\n> ";
cin>>restart;}
else{
cerr<<"Number is less than two!\n";
restart=1;
system("PAUSE");
system("cls");}}
return EXIT_SUCCESS;}

bool isPrime(int num)
{
int i, r;
bool prime (1);
for (i=2; i<= num; i++)
{
r=num/i;
if(r==0)
{
prime = 0;
}
}
return prime;}
Topic archived. No new replies allowed.