A positive integer n is said to be prime (or, "a prime") if and only if n is greater than 1 and is divisible only by 1 and n. For example, the integers 17 and 29 are prime, but 1 and 38 are not prime. Write a function named "is_prime" that takes a positive integer argument and returns as its value the integer 1 if the argument is prime and returns the integer 0 otherwise. Thus, for example:
cout << is_prime(19) << endl; // will print 1
cout << is_prime(1) << endl; // will print 0
cout << is_prime(51) << endl; // will print 0
cout << is_prime(-13) << endl; // will print 0
#include <iostream>
using std::cout;
using std::endl;
int is_prime(int n)
{
// 1 does not apply to prime numbers
if (n <=1)
{
return 0;
}
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
// example of how the function works
cout << is_prime(19) << endl; // will print 1
cout << is_prime(1) << endl; // will print 0
cout << is_prime(3) << endl; // will print 1
cout << is_prime(51) << endl; // will print 0
cout << is_prime(-13) << endl; // will print 0
return 0;
}
Comments
Leave a comment