Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding is_prime function with tests #41

Open
wants to merge 2 commits into
base: temp
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions isprime.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include <iostream>
#include <climits>
#include <cmath>

/* Update if you are testing more
* Assuming
*/
#define TESTS 7
#define TEST_INPUTS {-128, \
0, \
1, \
2, \
45, \
101, \
127}

#define EXPECTED_OUTPUT {false, \
false, \
false, \
true, \
false, \
true, \
true}

using namespace std;

/* is_prime checks whether the number is prime and returns true for any prime
* and positive integer and returns false for any other condition
*/

bool is_prime(long n) {
if(n <= 1) return false;
long test = sqrt(n), i = 0;
for(i = test; i > 1; i--){
if((n % i) == 0) return false;
}
return true;
}

/* prime_tester unit tests the is_prime for a set of inputs mentioned at the
* top
*/

void prime_tester(void) {
bool expected[TESTS] = EXPECTED_OUTPUT;
long inputs[TESTS] = TEST_INPUTS;
int i = 0;
for(i = 0; i < TESTS; i++){
if(expected[i] == is_prime(inputs[i])) {
cout<<"Test "<<i<<": Passed! Input: "<<inputs[i]<<endl;
} else {
cout<<"Test "<<i<<": Failed! Failing input: "<<inputs[i]<<endl;
}
}
}


/* Uncomment to test the code*/
//int main(void) {
// prime_tester();
// return 0;
//}