954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Program that determines if a number is prime

Hi,
I need help writing a function that determines if a number is prime. It has to print all the prime numbers between 1 and 10000
this is what i have...where i put a " */* " is where i need your help.....

#include<iostream>

using std::cout;
using std::endl;

#include<iomanip>

using std::setw;

/* write prototype for function prime */

int main()
{
  int count = 0;

  cout << "The prime numbers from 1 to 10000 are:\n";

  for (int loop =2; loop <= 10000; ++loop)

     if ( /* make call to function prime */  ) {
        ++count;
        cout << setw( 6 ) << loop;

     if ( count % 10 == 0)
        cout << '\n';
}

  cout << '\n' << "There were " << count
         << " prime numbers\n";

 return 0;
}
  bool prime (int n)
{
  for ( int i = 2; /*write loop condition */; i++ )

     if( /*write code to test if n is divisible by i */)
        return false;

   return true;
}


<< moderator edit: added [code][/code] tags >>

I need all the help i can get ;)

dark7angelx07
Newbie Poster
7 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

to call the function prime, it is just to add:
prime(loop)

a simple loop condiction is:
(n/2)+1 > i
since after 1/2 of the val of n there cant be a fraction of the n number.

and the test are simple ennuf:
if (n%i == 0)

zyruz
Junior Poster in Training
60 posts since Jun 2005
Reputation Points: 10
Solved Threads: 5
 

To find if a number n is prime, you can just loop through all the numbers from 2 to (n - 1) and see if any of them divide evenly, using the modulus operator. So your loop ending condition could be (i < n), and you know that i divides into n if (n % i) equals 0.

This is a dumb algorithm, though. Instead, you can loop through all the numbers from 2 to the square root of n and test them. No need to go all the way up to (n - 1). Because if a number more than the square root of n divides into n, then a number less than the square root of n also works.

You might also want to try figuring out a method that doesn't use a prime testing function, which uses an array (maybe some other time).

Making the call to the function prime would be the same as making any function call, would it not? prime(loop).

Rashakil Fol
Super Senior Demiposter
Team Colleague
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
 

Someone commented that to see if n is a prime you only have to check possible divisors < sqrt(n). In addition, you can decrease the computing time a lot by testing the divisor 2 , then 3, 5, 7..., skipping every other integer. The reason that this works is once you've determined that 2 is not a divisor you don't have to check 4, 6,8...or any even integer because if one of them were a divisor then so would 2 be a divisor. With a little ingenuity you can extend this to not testing multiples of 3 once you've determined that 3 is not a divisor, etc.

Actually, to produce a table of all the primes < 100000 (or, for that matter, of 1 million or ten million) there's a much better way called the sieve of Eritosthenes. (I think I spelled that all wrong). You can find it in many books. It's blindingly fast, using no divisions and a short code does the trick. Maybe this is what your instructor really wanted.

murschech
Junior Poster in Training
60 posts since Dec 2004
Reputation Points: 21
Solved Threads: 1
 

I think I read somewhere that to find out if a number is a prime, you dont have to check dividing upto n-1. Upto squareroot(n) is enough. check it out.

WolfPack
Postaholic
Moderator
2,051 posts since Jun 2005
Reputation Points: 572
Solved Threads: 115
 

i got a similar program too :

# include<iostream.h>
# include<conio.h>

void main()

{
	clrscr();

	int isprime(int);
	int value;

	//input
	cout<<"Enter a number to verify whether it is prime or not "<<endl;
	cout<<"Enter -1 to stop"<<endl;
	cin>>value;

	//output
	while (value!=-1)
		{

		if (isprime(value)==1)
			{
			cout<<"Yes the number is prime"<<endl;
			}
		else
			{
			cout<<"Sorry, not a prime"<<endl;
			}
		getch();
		clrscr();
		cout<<"Enter a number to verify whether it is prime or not "<<endl;
		cin>>value;

		}
}

	//calculation
	int isprime(int valuex)
		{
		int x,j;
		x=1;

		for (j=2 ; j<valuex/2 ; j++)
			{
			if ((valuex%j)==0) x=0;
			}

		if(x!=0) return 1;
		else return 0;
		}


<< moderator edit: added [code][/code] tags >>

:lol:
created on 6/25/2005

cpp noob
Newbie Poster
15 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

Hi , I had a question again for what you said above.....

So I would just write..... if prime(loop) ...Is that how I should write it??
OR if (prime(loop)) ???

What should I write for the prototype for function prime? (first line)


Thank you so much for helping me.....

dark7angelx07
Newbie Poster
7 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

Your program doesn't make use of the efficiencies I mentioned. For one thing, you test possible factors up to valuex/2 but you only have to go up to sqrt(valuex), which is much smaller. (For example, sqrt(100) is 10, much less that 100/2.) Also you increment trial divisors by one rather than 2. Finally, once you find a divisor (and so, you know the number's not a prime), you contiinue to try more divisors!

Here's my version.

#include <iostream>
using namespace std;

bool isaprime(long);

bool isaprime(long x)
{   long n;
    // is 2 a divisor?
    if ( x%2 == 0)
       return false;
    n = 3;
    while (n*n <=x)
    {   if (x%n == 0)
           return false;
        n += 2;
    }
    return true;
}

int main()
{   long x;
    while (1)
    {   cout <<"Enter a positive integer to check for primality, 0 to exit: ";
        cin >> x;
        if (x == 0)
        {   cout << "Thanks for the fun. Come again.\n";
            return 1;
        }
        if (isaprime(x))
           cout <<x<<" is a prime\n";
        else
           cout <<x<<" is not a prime\n";

   }

}


<< moderator edit: fixed [code][/code] tags (forward slash) >>

murschech
Junior Poster in Training
60 posts since Dec 2004
Reputation Points: 21
Solved Threads: 1
 

cpp noob
using your program, which tests for the integer input by the user,
how you could test all the numbers from 1 to 10,000? I duno i was all curious about it too.
:)
Mina

mina1984
Newbie Poster
16 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

i lucky have this program creted on the same day

# include
# include

void main()

{
clrscr();
int value, x, i, j;

//input
cout<<"Enter the value to which you want to find the prime numbers ";
cin>>value;

//calculation
for ( i=3 ; i<=value ; i++)
{
x=1;

for (j=2 ; j

cpp noob
Newbie Poster
15 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

Here are the correct codes:

/* write prototype for function prime */ = bool prime(int n);

if ( /* make call to function prime */ ) = if (prime(loop))


for ( int i = 2; /*write loop condition */; i++ )
=
for ( int i = 2; (n/2) + 1 > i; i++ )

if( /*write code to test if n is divisible by i */)
=
if( n%i == 0 )

dark7angelx07
Newbie Poster
7 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

this is a prime tester that uses the advises from post's here.

bool prime(int num)
{
    // all numbers from 1 and lower aint primes.
    if(num <= 1)
    {
         return false;
    }
    // 2 is a prime.
    if(num == 2)
    {
         return true;
    }
    // is 2 a divisor?
    if ( num%2 == 0)
    {
       return false;
    }
    
    for (int n=3;n*n <= num;n+=2)
    {   if (num%n == 0)
           return false;
    }
    // done testing, so return it as prime.
    return true;
}
zyruz
Junior Poster in Training
60 posts since Jun 2005
Reputation Points: 10
Solved Threads: 5
 

to check if a number is prime ,u could simply check if the number equals (6x+ or - 1) for any x

sowmya588
Newbie Poster
1 post since Feb 2008
Reputation Points: 10
Solved Threads: 0
 

I have made someyhing like this before.
Here it is:

bool CheckPrime(unsigned long num)
{
     unsigned long long int x = 2;
     bool prime;
     
     if (num < 4)
     {
     switch (num)
     {
     case 1:
     prime = false;
     break;
     
     case 2:
     prime = true;
     break;
     
     case 3:
     prime = true;
     break;
     
     case 4:
     prime = false;
     break;
     }
     }
     
     else
     {
while (x < (num / 2) + 1)
{
      if (num % x == 0)
      {
      prime = false;
      break;
      }
      else 
      {
      prime = true;
      x++;
      }
}
      }

return prime;
}
TheBeast32
Posting Whiz in Training
236 posts since Dec 2007
Reputation Points: 79
Solved Threads: 6
 

If num < 4, how will it ever be equal to 4 for the switch? Might you have meant 0?

Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
 

hey, could any one find the error in this program please. i wrote the thing but theres sumthing wrong with it. :(..thank you

#include
#include

#define TRUE 1;
#define FALSE 0;

int main()
{
int number;

getNumber(*number);

if (isPrine(number))
cout << "\n" << number << is a prime number\n";
else
cout << "\n" << number << is not a prime number\n";

return 0;
}

void getNumber(int &number)
{
cout << "Please enter a positive number ";
cin >> number;
if (!cin.good())
{
printf("Invalid number entered\n");
exit(1);
}
}

int isPrime(int number)
{
int count, s;

/* Every even number is not prime */
if (number % 2 == 0) return TRUE;

/* check every odd number up to the square root of the number */
s = sqrt(number);
for (count=3; count<=s; count+=2);
{
if (number % count == 0) return TRUE;
}
return FALSE;
}

Yaka
Newbie Poster
11 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

getNumber(*number); this is wrong. Get rid of the *, as you are passing it by reference. if (isPrine(number)) should be spelt correctly

you will have to declare your functions before the main() routine, so put:

void getNumber(int &number);
isPrime(number);


on the line before main()

As an aside, why is checking division against every odd number the best way to do it? I would have thought it would be quicker to test division against every prime number less than sqrt(number)... Obviously if a number is not divisible by e.g. 5 (prime), it won't be divisible by any multiple of 5 (which obviously won't be prime).

dougy83
Posting Whiz in Training
275 posts since Jun 2007
Reputation Points: 85
Solved Threads: 45
 

And the number 1 thing wrong with it is that the test function returns TRUE for non-primes and FALSE for primes!!!

Why the #define TRUE and FALSE when C++ has the perfectly good built in bool type, with values true and false ?

ps - you're responding/reopening a three year old thread, that saw a rebirth three weeks ago. Wasn't there enough discussion for you to find what you needed?

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

THE ULTIMATE SOLUTION IS THIS

Just change 100 to wherever you want it to stop.

Posted by James. :icon_cool:

#include "iostream"
#include "cstdlib"
#include "cmath"

using namespace std;




//Determines the prime numbers in a loop from 2 to 100
int main () {


int p_number;



for ( p_number = 2; p_number <= 100; p_number++)

{  
	if (p_number == 2) {cout << "2 is prime\n";}
    if (p_number == 3) {cout << "3 is prime\n";}
 if (p_number == 5) {cout << "5 is prime\n";}
if (p_number == 7) {cout << "7 is prime\n";}
	if((p_number % 2) != 0){ 
		
		if((p_number % 3) != 0){
		
			if((p_number % 5) != 0){
              if((p_number % 7) != 0){
				  if((p_number % 9) != 0){
			cout << p_number << " is prime\n";
				  }
			  }
			}
		}
}

}

system ("PAUSE");


return 0; 

}
terminator0031
Newbie Poster
1 post since Mar 2008
Reputation Points: 10
Solved Threads: 0
 
THE ULTIMATE SOLUTION IS THIS


Only if you can't program... :icon_rolleyes:

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You