Write a function isPrime that takes an integer a, returns 1 if a is prime and returns 0 if a is not prime.
Two integers a and b are said to be coPrime if the only positive integer that divides both is 1. Write a function areCoPrime that takes two integers a and b, returns 1 if a and b are coprime, 0 if not.
Write a main program that asks the user to enter two integers a and b and determines if a and b are primes or not, coprime or not.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#include<math.h>
int isPrime(int a) {
int i;
for (i = 2; i <= sqrt(a); i++)
if (a%i == 0)
return 0;
return 1;
}
int areCoPrime(int a, int b) {
int i;
for (i = 2; i <= a && i <= b; i++)
if (a%i == 0 && b%i == 0)
return 0;
return 1;
}
void main() {
int a, b;
printf("Enter two numbers:");
scanf("%d%d", &a, &b);
if (isPrime(a) == 1)
printf("%d is prime\n", a);
else
printf("%d is not prime\n", a);
if (isPrime(b) == 1)
printf("%d is prime\n", b);
else
printf("%d is not prime\n", b);
if (areCoPrime(a, b) == 1)
printf("%d and %d are coprime\n", a, b);
else
printf("%d and %d are not coprime\n", a, b);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Interchange diagonals of a square matrix