Skip to content

Instantly share code, notes, and snippets.

@lidio601
Created November 28, 2019 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lidio601/b9b78240f6e20d541b8cf2def4a1bf47 to your computer and use it in GitHub Desktop.
Save lidio601/b9b78240f6e20d541b8cf2def4a1bf47 to your computer and use it in GitHub Desktop.
C test to check if a number is prime
#include <stdbool.h>
#ifndef Solution_INCLUDED
#define Solution_INCLUDED
bool IsPrime(int input);
#endif
#include "solution.h"
#include <stdbool.h>
bool IsPrime(int input)
{
// those are NOT prime by definition
if (input < 1) {
return false;
}
// those are prime by definition
// 1 of course
// 2 is the only even number that is also prime
if (input == 1 || input == 2) {
return true;
}
// even number can't be prime
if (input % 2 == 0) {
return false;
}
// loop over all the odd number
// from 3 up to 1/2 of input
for (int divider = 3; divider < input / 2; divider+=2) {
if (input % divider == 0) {
// if input is divisible by divider
// it means that input is NOT prime
return false;
}
}
// if we reach this point
// it means that we couldn't find
// another divider rather than 1 and input itself
// so input IS prime
return true;
}
#include <stdbool.h>
#ifndef Solution_INCLUDED
#define Solution_INCLUDED
bool IsPrime(int input);
#endif
#include "solution.h"
#include "unity.h"
#include <stdbool.h>
void setUp(void)
{
}
void tearDown(void)
{
}
void test1(void)
{
int input = 3;
bool expected = true;
bool output = IsPrime(input);
TEST_ASSERT_EQUAL(expected, output);
}
void test2(void)
{
int input = 4;
bool expected = false;
bool output = IsPrime(input);
TEST_ASSERT_EQUAL(expected, output);
}
void test3(void)
{
int input = 7;
bool expected = true;
bool output = IsPrime(input);
TEST_ASSERT_EQUAL(expected, output);
}
void test4(void)
{
int input = 21;
bool expected = false;
bool output = IsPrime(input);
TEST_ASSERT_EQUAL(expected, output);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment