Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C] Prime number function
#1
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.
Reply


Messages In This Thread
[C] Prime number function - by Commodore - 10-11-2010, 12:41 PM
RE: [C] Prime number function - by Disease - 10-11-2010, 01:04 PM
RE: [C] Prime number function - by Commodore - 10-11-2010, 01:11 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  C++ stdio.h rename function problem AceInfinity 2 1,031 01-14-2012, 08:39 PM
Last Post: AceInfinity
  [C] Factorial function Commodore 1 900 11-28-2010, 07:13 AM
Last Post: RANA
  Problem with a member function of a class charnet3d 2 996 10-31-2009, 03:22 AM
Last Post: charnet3d

Forum Jump:


Users browsing this thread: 2 Guest(s)