Support Forums

Full Version: [C] Prime number function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm in the process of learning C, so to exercise my loop knowledge, I created a little function to determine if a number is prime or not. A return value of 1 indicates that it is; 0 that it isn't.

Usage:
Code:
isprime(number to assess);

And here's the code:
Code:
int isprime(int x)
{
    int prime = 0;
    int i = 0;    

    for (i = (x - 1); i > 1; --i)
    {
        if ((x % i) == 0)
        {
            prime = 0;
            return prime;
        }
    
        else
        {
            prime = 1;
        }
    }
    return 1;
}

I guess beginners could learn from it. It's pretty much compatible with C++ too.
(10-11-2010, 12:41 PM)cerm Wrote: [ -> ]I'm in the process of learning C, so to exercise my loop knowledge, I created a little function to determine if a number is prime or not. A return value of 1 indicates that it is; 0 that it isn't.

Usage:
Code:
isprime(number to assess);

And here's the code:
Code:
int isprime(int x)
{
    int prime = 0;
    int i = 0;    

    for (i = (x - 1); i > 1; --i)
    {
        if ((x % i) == 0)
        {
            prime = 0;
            return prime;
        }
    
        else
        {
            prime = 1;
        }
    }
    return 1;
}

I guess beginners could learn from it. It's pretty much compatible with C++ too.

Your code is a little redundant and could be re-factored. For example, you're really not using the prime variable. You return it in the case of true, but you don't use it in the case of false. Thus all you're really doing is needlessly setting a variable. And if you remove the prime variable entirely your ELSE statement becomes unnecessary.

And while it's completely arbitrary, the de facto value for TRUE in C is 1. Obviously if it's just you using a function it doesn't matter. But releasing code that uses unconventional values can lead to confusion. You may want to do yourself a favor and just use the standard conventions at all times. Your code will be more self-explanatory that way.

Either way, it looks like you understand the FOR loop. If you're still feeling uncomfortable with WHILE loops I'd recommend rewriting this to use one instead of FOR, just for the learning experience.

Code:
int isPrime (int x)
{
  int i = 0;    

  for (i = (x - 1); i > 1; --i)
  {
    if ((x % i) == 0)
    {
      return 1;
    }
  }
  
  return 0;
}
I see what you're saying. Thanks for clearing me up.