Page 1 of 1

Programming Question

Posted: Sat Apr 12, 2008 7:10 pm
by Kazaxat
ok so im currently taking a C++ class and its hard as hell and the professor want us to write a boolean function that returns whether a number is a prime number or not.

how would i go about that? is this how? :


Code: Select all

bool IsNumPrime( int num)
{
 if ( num = 2,3,5,7,11,13,17...)
   return true;
 else
   return false;
}

Re: Programming Question

Posted: Sat Apr 12, 2008 7:43 pm
by Casey613
Wrong, wrong wrong, that'd never work, remember this scripting is done with algorithms
Here's a website that will help you http://pastebin.ca/982660
You only have to convert to C++, easy imo

Re: Programming Question

Posted: Sat Apr 12, 2008 7:44 pm
by DotCom
You logic is not correct. I wrote a couple of lines, didnt have the time to test it but the logic is correct. Just play with it around a bit and debug the program to see how it works. Hope it helps.

Code: Select all

  bool count = false;
   int num;
   cin >> num;

   
   for(int i=1;i<num/2; i++)
   {
      if (num%i!=0)
      {
         count=true;
      }
      else
         count=false;
   }
   cout<<"the number is :"<<count;

   return 0;

Re: Programming Question

Posted: Sat Apr 12, 2008 8:10 pm
by Casey613
As you SHOULD know, a prime number is a whole number
*That's larger than one
*That's divisible only by one and itself ('divisible' meaning: there's NO remainder after division)


Here, a simple but very brute force approach would be something like this:

Code: Select all

bool NumIsPrimer(int num)
{
   if(num < 2) return false;
   int sqr = sqrt(num);
   int try_to_divide = 1;
   while(++try_to_divide < sqr)
   {
      if(num % try_to_divide == 0) return false;
   }
   return true;
}



The thing with what you coded is that it will only work in as far as you already supply it with prime #s.
The trick is to let the program calculate whether the numbers are prime or not.

Re: Programming Question

Posted: Sat Apr 12, 2008 8:33 pm
by NuclearSilo

Code: Select all

bool isPrime(int num){
   if (num<=3) return true;

   int limit=sqrt(num);

   for (int i=2; i<=limit; i++){
      if (num%i==0) return true;
   }

   return false;
}


add also the header #include <math.h>