COMP2243 - Programming and Problem Solving

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Repetitions/Loops WhileLoop.java LoopWithCounter.java LoopWithSentinel.java LoopWithFlag.java SimpleInterest.java Factorial.java Fibnonacci.java PrimeNumber.java GCD.java PopulationGrowth.java ForLoop.java DoWhileLoop.java FileIO_Tickets.java FileIO_Salary.java NestedLoop.java



GCD Program


Description

This program uses the Euclidean algorithm to calculate the greatest common divisor of two positive integers.

Step 1: Assign m to the larger number and n to the smaller number

Step 2: Divide m by n to get the remainder r

r = m % n

Step 3:

If r is not 0

    Assign m to n (m = n)

    Assign n to r (n = r)

    Repeat Step 2

Otherwise

    n is the answer

Associated Concepts:

while loop

Algorithm:

Input two positive integers m and n from the keyboard

If m is smaller than n, swap them

Divide m by n to get the remainder r: r = m % n

Use a while to check r (as long as r is not 0)

    m = n

    n = r

    r = m % n

Once the while loop is ended, n is the answer

Source Code



Sample Run



Video