Loop Assignment 3 — Check Coprime Numbers Using While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Check Whether Two Numbers Are Coprime Using a While Loop

📑 On this page:
  • What "Coprime" Really Means
  • Why GCD Decides the Answer
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What "coprime" or "relatively prime" actually means, in everyday terms
  • Why two numbers are coprime exactly when their GCD equals 1
  • How to reuse the Euclidean algorithm from the GCD assignment with one tiny change
  • Why zero makes the test fail — and why that's the honest answer
  • How this idea shows up in fractions, cryptography, and hashing

What "Coprime" Really Means

Two numbers are coprime when they share no common factor other than 1. That's the whole idea — nothing more complicated. Eight and fifteen are coprime because neither 3 nor 5 divides 8, and no other factor of 15 divides 8 either. Twelve and eighteen are not coprime, because both are divisible by 6. Nine and twenty-seven are not coprime, because both are divisible by 9.

The phrase "relatively prime" means the same thing — don't let the terminology throw you. Coprime is about the pair, not about either number individually. Twelve alone isn't coprime or not-coprime; twelve and eighteen together are not coprime, twelve and thirty-five together are. Change one of the pair and the answer can flip entirely.

Once you've seen the GCD assignment, the connection is immediate: two numbers are coprime exactly when their GCD is 1. If the GCD is 2, they share a factor of 2. If it's 6, they share 2, 3, and 6. If it's 1, there's nothing shared except the universal 1. So the coprimality test collapses to: compute the GCD, compare it with 1. The loop is the same loop.

💡 In one line: two numbers are coprime if and only if GCD(a, b) == 1. That's the whole test — everything else is a consequence.

Diagram showing factor breakdown of 8 and 15 with no factor in common, next to 12 and 18 with shared factors 2, 3, and 6

Why GCD Decides the Answer

Here's the reasoning in one paragraph. By definition, the GCD of a and b is the largest number that divides both. If it's 1, then no positive integer bigger than 1 divides both — that is, they have no common factor besides 1. Which is exactly what "coprime" means. Conversely, if they have no common factor besides 1, then 1 is the only common divisor, so 1 is the largest, so it's the GCD. The two statements are equivalent, not just similar.

So the algorithm is:

  1. Read two integers, take absolute values.
  2. If either is zero (or both), report "not coprime" — GCD will not be 1.
  3. Apply Euclid's algorithm in a while loop: while (b != 0) { r = a % b; a = b; b = r; }. After the loop, a is the GCD.
  4. If a == 1, the numbers are coprime. Otherwise, they aren't.

Note that this is not just a rehash of the GCD program — the purpose is different. There we wanted the GCD value itself; here we want a yes/no answer, and the GCD is just the machinery. In real code you'd sometimes stop the Euclidean loop early as soon as the GCD drops to 1, since it can't go any lower. That optimisation matters when you're testing thousands of pairs (as in hash-table design), not when you're checking one pair by hand.

Pair GCD Coprime? Why
8, 151YesNo factor in common beyond 1
12, 186NoBoth divisible by 6
9, 281Yes9 = 3², 28 = 2²·7 — disjoint
17, 3417NoOne divides the other
1, any1Yes1 has only itself as a factor
0, 55NoEvery number divides 0, so the shared factor is 5

Complete C Program

Program: check coprime using a while loop

#include <stdio.h>

/* Returns the GCD of two non-negative integers using Euclid's algorithm */
int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int main(void) {
    int a, b;

    printf("Enter two integers: ");
    if (scanf("%d %d", &a, &b) != 2) {
        printf("Invalid input.\n");
        return 1;
    }

    /* Work with absolute values — coprime is a property of magnitudes */
    if (a < 0) a = -a;
    if (b < 0) b = -b;

    /* Zero is never coprime with anything, because every number divides 0 */
    if (a == 0 || b == 0) {
        printf("Not coprime. (Zero is never coprime with any integer.)\n");
        return 0;
    }

    int g = gcd(a, b);

    if (g == 1) {
        printf("Coprime. (GCD = %d)\n", g);
    } else {
        printf("Not coprime. (GCD = %d, so both numbers share a factor.)\n", g);
    }

    return 0;
}
                                    

And here is the same logic without a separate function, in case the assignment asks you to keep everything inside main:

Single-function version (all logic inside main)

#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter two integers: ");
    scanf("%d %d", &a, &b);

    if (a < 0) a = -a;
    if (b < 0) b = -b;

    if (a == 0 || b == 0) {
        printf("Not coprime.\n");
        return 0;
    }

    /* Euclid's algorithm on a and b, with x and y as working copies */
    int x = a, y = b;
    while (y != 0) {
        int r = x % y;
        x = y;
        y = r;
    }

    if (x == 1)
        printf("Coprime.\n");
    else
        printf("Not coprime. GCD = %d\n", x);

    return 0;
}
                                    

The two versions produce the same result. The first is more reusable (the gcd function can be called from other programs), and it matches the structure you'd use in real C code. The second is closer to what exam papers often ask for: "write a program" that does the whole job inside main.

Program Output

Enter two integers: 8 15
Coprime. (GCD = 1)
                                

Try a few more. Twelve and eighteen should say "Not coprime, GCD = 6." Seventeen and thirty-four should say "Not coprime, GCD = 17." Nine and twenty-eight should say "Coprime." Any pair with a zero should say "Not coprime" without even entering the loop. Then try 1 and 999999 — coprime, because 1 divides everything and nothing else divides it.

Step-by-Step Explanation

Let's walk through 8 and 15 first, then look at the pieces that catch people out.

1. Reading and normalising input

scanf checks that two integers were actually read. Then the two if lines convert negatives to positives — the coprimality of -8 and 15 is the same as that of 8 and 15, but negative operands inside a % b can produce negative remainders and send the loop into confusing territory. Two lines of normalisation remove the problem entirely.

2. The zero check before the loop

If either input is zero, the loop never gets a chance to run correctly. Worse, 0 % 0 is undefined behaviour. More importantly, zero is never coprime with any integer, because every positive number divides zero — so the "largest common factor" is whatever the other number happens to be. The explicit early return states this in plain language rather than letting the loop produce a misleading answer.

3. The Euclidean while loop

The loop reduces the pair by replacing (x, y) with (y, x % y). For 8 and 15:

  1. r = 8 % 15 = 8; x = 15, y = 8
  2. r = 15 % 8 = 7; x = 8, y = 7
  3. r = 8 % 7 = 1; x = 7, y = 1
  4. r = 7 % 1 = 0; x = 1, y = 0
  5. y == 0 — exit. GCD = 1.

Compare with 12 and 18: r = 12, then r = 6, then r = 0, ending with x = 6. Larger GCD, fewer iterations. That's the usual pattern — when the numbers share a big factor, the loop finishes faster.

4. Why the loop is the same as the GCD program

It has to be. The coprimality test is a GCD computation with a comparison at the end. The only thing different is what we do with the result: print "Coprime" or "Not coprime" rather than the number itself. This is a good example of how one good algorithm can answer several questions — once you have a correct gcd function, the coprime test is one line, the LCM is another, and the reduce-a-fraction program is a third.

5. Why every number is coprime with 1

1's only positive divisor is itself. So the set of common divisors of 1 and n is {1}. The GCD is therefore 1, and the pair is coprime. This is the reason 1 is called the "unit" in number theory — it doesn't really act like a number when you're thinking about factorisation, and its coprimality with everything is part of that.

6. Why consecutive integers are always coprime

A nice fact worth remembering: n and n+1 are always coprime. Suppose some d > 1 divides both. Then it divides their difference, which is 1. No integer greater than 1 divides 1, contradiction. So GCD(n, n+1) = 1 for every n. Try 14 and 15, 999 and 1000, or 1000000 and 1000001 — all coprime. This one comes up in interview puzzles regularly.

7. The early-exit optimisation

If you only care about the yes/no answer and not the actual GCD, you can exit the loop early when x drops to 1. Once it's 1, no amount of further Euclid steps will lower it. In a program testing thousands of pairs (typical in hash-table design), this can save a noticeable chunk of time. For a one-off check like this program, it isn't worth the extra code. But it's a useful pattern to know — "can I stop the loop as soon as I know the answer?" is often the difference between a clever solution and a clumsy one.

🎯 Remember this: two numbers are coprime exactly when their GCD is 1. Compute the GCD with the same Euclidean while loop from the earlier assignment, then compare the result with 1. Zero is never coprime with anything — report that early. And remember the free fact: consecutive integers are always coprime.

Frequently Asked Questions

1. What does "coprime" actually mean — and is it the same as "relatively prime"?

Yes, they mean the same thing. Two integers are coprime (or relatively prime) when the only positive integer that divides both is 1. Equivalently, their GCD is 1. The pair (8, 15) is coprime, (12, 18) is not. Note that coprime is a property of the pair, not of either number on its own — you can't call 8 "coprime" without naming what it's coprime to.

2. Why is the GCD test enough — isn't there a case where two numbers share a factor but the GCD is 1?

No, that's impossible by definition. The GCD is the largest common divisor. If a common divisor bigger than 1 exists, then the GCD is at least that big — so the GCD can't be 1. Conversely, if the GCD is 1, the only common divisor is 1 — so no shared factor above 1 exists. The two conditions are exactly equivalent; you can't have one without the other.

3. Are 0 and 1 coprime?

No. Zero is never coprime with anything. Here's why: every positive integer divides 0 (0 = k × 0 for any k). So the set of common divisors of 0 and 1 is all positive integers that divide 1, which is just {1} — fine, the GCD is 1 by that reading. But it's cleaner to say "GCD(0, n) = |n|", which gives GCD(0, 1) = 1. And yet we say 0 is not coprime with anything because "coprime" is usually defined only for positive integers, and the extended property of 0 (dividing nothing but being divided by everything) breaks the natural intuition. The program reports 0-containing pairs as "not coprime" — that's the safer, more conventional answer, and it avoids the weird case GCD(0, 0) = 0, which would have been reported as coprime if we weren't careful.

4. Can I test coprime-ness without computing the full GCD?

You can stop the Euclidean loop early if either input drops to 1, because the GCD can't get any smaller. In a single test that saves at most a few iterations — not worth the added code. In a program that tests many pairs (e.g., hash-table design where you keep coprime table sizes), it can save real time. For this assignment, the plain version is clearer and just as correct.

5. Are consecutive numbers always coprime?

Yes, always. If n and n+1 shared a factor d > 1, then d would divide their difference, which is 1 — impossible for d > 1. So GCD(n, n+1) = 1 for every integer n. This comes up in interview puzzles and in some algorithms (like choosing an odd number that's coprime with its neighbours). Try 99 and 100, or 1000000 and 1000001 — you'll see it holds.

6. Where is the coprimality test used in real software?

Three places come up often. First, hash-table sizing — you want the table size and the hash increment to be coprime so the probe sequence visits every slot. Second, RSA encryption — the public exponent must be coprime with φ(n), the totient. Third, reducing fractions — you divide numerator and denominator by their GCD; if the GCD is 1, the fraction is already in lowest terms. Coprimality is a small piece of mathematics that keeps showing up in engineering.

💡 Tip: Once this program makes sense, notice that you already have the gcd function. Try rewriting assignments 1 (GCD), 2 (LCM), and 3 (coprime) as three tiny main functions that all call the same gcd — you'll see how a well-written helper multiplies its value. That's the pattern the rest of the loop series uses, and it's what real C code looks like.

📖 Related Tutorials

  • 1. Find the GCD of Two Numbers Using a While Loop
  • 2. Find the LCM of Two Numbers Using a For Loop
  • 4. Find All Common Divisors of Two Numbers Using a For Loop
  • 5. GCD of Three Numbers Using Nested Loops
  • 30. Check Whether Two Integers Are Amicable Using a For Loop
  • While Loop
  • Do-while Loop
  • All 30 Loop Assignments

Previous Topic: -->> 2. Find the LCM of Two Numbers Using a For Loop   ||   Next Topic: -->> 4. Find All Common Divisors of Two Numbers Using a For Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.