2020-08-11 18:01:10 +03:00
|
|
|
/**
|
|
|
|
* @file
|
|
|
|
* @brief Program to identify if a number is [prime
|
|
|
|
* number](https://en.wikipedia.org/wiki/Prime_number) or not
|
|
|
|
*/
|
|
|
|
#include <assert.h>
|
2018-03-23 23:08:21 +03:00
|
|
|
#include <math.h>
|
2020-08-11 18:01:10 +03:00
|
|
|
#include <stdbool.h>
|
2020-05-29 23:23:24 +03:00
|
|
|
#include <stdio.h>
|
2017-10-19 11:38:10 +03:00
|
|
|
|
2020-08-11 18:01:10 +03:00
|
|
|
/**
|
|
|
|
* Check if a given number is prime number or not
|
|
|
|
* @param x number to check
|
|
|
|
* @return `true` if given number is prime number, otherwise `false`
|
|
|
|
*/
|
|
|
|
bool isPrime(int x)
|
2020-05-29 23:23:24 +03:00
|
|
|
{
|
|
|
|
if (x == 2)
|
|
|
|
{
|
2020-08-11 18:01:10 +03:00
|
|
|
return true;
|
2019-10-12 21:21:30 +03:00
|
|
|
}
|
2020-05-29 23:23:24 +03:00
|
|
|
if (x < 2 || x % 2 == 0)
|
|
|
|
{
|
2020-08-11 18:01:10 +03:00
|
|
|
return false;
|
2019-10-12 21:21:30 +03:00
|
|
|
}
|
2020-05-29 23:23:24 +03:00
|
|
|
|
2019-10-12 21:21:30 +03:00
|
|
|
double squareRoot = sqrt(x);
|
2020-05-29 23:23:24 +03:00
|
|
|
|
|
|
|
for (int i = 3; i <= squareRoot; i += 2)
|
|
|
|
{
|
2019-10-12 21:21:30 +03:00
|
|
|
if (x % i == 0)
|
2020-08-11 18:01:10 +03:00
|
|
|
{
|
|
|
|
return false;
|
|
|
|
}
|
2017-10-19 11:38:10 +03:00
|
|
|
}
|
2020-08-11 18:01:10 +03:00
|
|
|
return true;
|
2017-10-19 11:38:10 +03:00
|
|
|
}
|
|
|
|
|
2020-08-11 18:01:10 +03:00
|
|
|
/**
|
|
|
|
* Test function
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
void test()
|
|
|
|
{
|
|
|
|
/* all the prime numbers less than 100 */
|
|
|
|
int primers[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
|
|
|
|
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};
|
|
|
|
for (size_t i = 0, size = sizeof(primers) / sizeof(primers[0]); i < size;
|
|
|
|
++i)
|
|
|
|
{
|
|
|
|
assert(isPrime(primers[i]));
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Example Non-prime numbers */
|
|
|
|
int NonPrimers[] = {-1, 0, 1, 4, 6, 8, 9, 10};
|
|
|
|
for (size_t i = 0, size = sizeof(NonPrimers) / sizeof(NonPrimers[0]);
|
|
|
|
i < size; ++i)
|
|
|
|
{
|
|
|
|
assert(!isPrime(NonPrimers[i]));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Driver Code
|
|
|
|
* @return None
|
|
|
|
*/
|
2020-05-29 23:23:24 +03:00
|
|
|
int main()
|
|
|
|
{
|
2020-08-11 18:01:10 +03:00
|
|
|
test();
|
2017-10-19 11:38:10 +03:00
|
|
|
return 0;
|
|
|
|
}
|