Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
prime.c File Reference

Program to identify if a number is prime number or not. More...

#include <assert.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
Include dependency graph for prime.c:

Functions

bool isPrime (int x)
 Check if a given number is prime number or not. More...
 
void test ()
 Test function. More...
 
int main ()
 Driver Code. More...
 

Detailed Description

Program to identify if a number is prime number or not.

Function Documentation

◆ isPrime()

bool isPrime ( int  x)

Check if a given number is prime number or not.

Parameters
xnumber to check
Returns
true if given number is prime number, otherwise false
17 {
18  if (x == 2)
19  {
20  return true;
21  }
22  if (x < 2 || x % 2 == 0)
23  {
24  return false;
25  }
26 
27  double squareRoot = sqrt(x);
28 
29  for (int i = 3; i <= squareRoot; i += 2)
30  {
31  if (x % i == 0)
32  {
33  return false;
34  }
35  }
36  return true;
37 }

◆ main()

int main ( void  )

Driver Code.

Returns
None
68 {
69  test();
70  return 0;
71 }
Here is the call graph for this function:

◆ test()

void test ( void  )

Test function.

Returns
void
44 {
45  /* all the prime numbers less than 100 */
46  int primers[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
47  43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
48  for (size_t i = 0, size = sizeof(primers) / sizeof(primers[0]); i < size;
49  ++i)
50  {
51  assert(isPrime(primers[i]));
52  }
53 
54  /* Example Non-prime numbers */
55  int NonPrimers[] = {-1, 0, 1, 4, 6, 8, 9, 10};
56  for (size_t i = 0, size = sizeof(NonPrimers) / sizeof(NonPrimers[0]);
57  i < size; ++i)
58  {
59  assert(!isPrime(NonPrimers[i]));
60  }
61 }
Here is the call graph for this function:
isPrime
bool isPrime(int x)
Check if a given number is prime number or not.
Definition: prime.c:16
test
void test()
Test function.
Definition: prime.c:43