Help on correcting this code on Dev C++

Ok first of all heres the question
Write a C++ function isPrimeNumber prototyped by
bool isPrimeNumber (long num);
that return true if num is a prime number and returns false if otherwise. Then write a driver program that finds and displays all the prime numbers between 1 and 1000, and also displays the total number of the prime numbers found this way. We note that a positive integer num is a prime number if and only if none of the integers from 2 to (num-1) can divide num completely.

Now heres my code (So far) which i cant seem to get to work, im only at beginner stage as well still learning alot


#include<iostream>
using namespace std;
int main ()
{
bool isPrimeNumber(int number)
//determines if the number is prime or not

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

}



int lower limit = 1;
int upperlimit = 1000;

for(int i=lowerLimit; i<=upperLimit; i++)

{

if(isPrimeNumber(i))

{

cout<<i<<endl;

}

}


Thats my code, im using Dev C++, and cant seem to get this code to work, i've tried correcting a few things. Any hints,tips, corrections etc would be greatly appreciated. Thank you
You can't define a function inside of main. Move it to outside/above main.

Also...I would define lowerlimit/upperlimit as const int instead of just int, and inside of isPrime(), you can just return false as soon as you see it's divisible by i instead of using another loop condition.
By the way, maybe I'm wrong but a prime number isn't not dividable by two. Prime numbers only divide by one and themselves. I just glanced at what you were doing but this doesn't seem like the way to find prime numbers at a glance, maybe someone could explain why this would?

EDIT: Nevermind, I'm a dumbass. Sorry xD
Last edited on
4 isn't prime because it is divisible by 2. Since for the loop goes from 2 to the number-1, if you put 2 in, it will work as expected.

http://en.wikipedia.org/wiki/Prime_number#Testing_primality_and_integer_factorization

See "Trial Division". The code actually goes to the number-1 here, but it you would obtain the same result anyway.
Topic archived. No new replies allowed.