Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,402 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,108 people online right now. Registration is fast and FREE... Join Now!




Function determining a prime number

 
Reply to this topicStart new topic

Function determining a prime number

loulz
23 Oct, 2006 - 10:33 AM
Post #1

New D.I.C Head
*

Joined: 23 Oct, 2006
Posts: 3


My Contributions
CODE
for (int i=0; i<=n; i++)
if (n%i !=0 )
cout<<"The number"<<i<<"is prime"<<endl;


AM I DOING THE RIGHT THING HERE?

Also, can someone plzz give me a small hint on that:
if we are given any number n then what is the upper number that we can divide n to be sure that it is prime.
User is offlineProfile CardPM
+Quote Post

Amadeus
RE: Function Determining A Prime Number
23 Oct, 2006 - 10:45 AM
Post #2

g++ -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 12,230



Thanked: 40 times
Dream Kudos: 25
My Contributions
A modulus return of zero is not the only determing factor for a prime number...9 into 16 returns a non zero modulus, but 9 is not prime. A prime number is one that cannot be divided evenly by any number except one and itself. Take a look at the following example:
CODE

#include <iostream>
using namespace std;

bool isPrime(int factor);

int main(void)
{
  int orignum;
  cout<<"Please enter an integer value:"<<endl;
  cin>>orignum;
  for(int i=1;i<=orignum;i++)
  {
     if((orignum%i)==0 && isPrime(i))
     {
            cout<<i<<" is a prime factor of "<<orignum<<endl;
     }
  }
  return 0;
}

bool isPrime(int factor)
{
   bool retValue = true;
   for(int i=1;i<=factor;i++)
   {
      if(((factor%i)==0) && i!=1 && i!=factor)
         retValue = false;
   }
   return retValue;
}

It looks for prime factors of a number, which is what I assume you are trying to do here.
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/5/08 03:10AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month