Lets write a C program to check whether two positive numbers entered by the user are Co-Prime numbers / Relative Prime Numbers or not using function / method.
Co-Prime numbers / Relative Prime Numbers: Two numbers are said to be co-prime or relative prime numbers if they do not have a common factor other than 1.
OR
Two numbers whose Greatest Common Divisor(GCD) is 1 are known as Co-Prime or Relative Prime Numbers.
Factors of a number: All the numbers which perfectly divide a given number are called as Factors of that number.
Note: User entered numbers(to check for co-prime) do not require to be prime numbers.
Complete logic is present in our previous day video tutorial, please watch it before continuing: C Program To Find Two Numbers are Co-Prime or Not
Related Read:
C Program To Find Prime Number or Not using While Loop
C Program to Find Factors of a Number using For Loop
Biggest of Two Numbers Using Ternary Operator: C
C Program to Find GCD or HCF of Two Numbers
Video Tutorial: C Program To Find If Two Numbers are Co-Prime or Not using Function
#include<stdio.h> int coprime(int num1, int num2) { int min, count, flag = 1; min = num1 < num2 ? num1 : num2; for(count = 2; count <= min; count++) { if( num1 % count == 0 && num2 % count == 0 ) { flag = 0; break; } } return(flag); } int main() { int n1, n2; printf("Enter 2 positive numbers\n"); scanf("%d%d", &n1, &n2); if( coprime(n1, n2) ) { printf("%d and %d are co-prime numbers.\n", n1, n2); } else { printf("%d and %d are not co-prime numbers.\n", n1, n2); } return 0; }
Output 1:
Enter 2 positive numbers
8
15
8 and 15 are co-prime numbers.
Output 2:
Enter 2 positive numbers
12
15
12 and 15 are not co-prime numbers.
Note:
coprime() method returns 1 or 0 value. If it returns 1, then the code inside if block gets executed. If it returns 0, then the code inside else block gets executed.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert