C Programming Exercise 2

advertisement
Computer and Information Technology 2007
Computer and Information Technology 2007
C Programming - Exercise 2
Euclidean Algorithm (輾轉相除法)
1.
Programming Exercise
By using Euclidean Algorithm, find the greatest common divisor (gcd), a.k.a. highest common
factor (HCF), of two positive integers from the user input.
Pseudo-code:
Step 1. Get two positive integers A and B from the user.
Step 2. Copy the larger number to X, and the smaller number to Y.
Step 3. Find out the remainder R when X is divided by Y.
Step 4. If R is not zero, then
a) Replace X with the value of Y
b) Replace Y with the value of R
c) Repeat steps 2-4.
Step 5. Y is the GCD.
Step 6. If the GCD is 1
a) Then output “The numbers … are co-prime”.
b) Else output the GCD of the two numbers.
Sample output of the program (text in italic are user’s input):
Please enter two positive integers: 32256 6624
The GCD of 32256 and 6624 is 288.
Please enter two positive integers: 120 23
The numbers 120 and 23 are co-prime.
Please enter two positive integers: -1 0
Invalid Input! Program exiting...
a)
Start from writing a simple program that works only once. That is, asks for two numbers,
calculates and displays the GCD and then exits.
b) Then modify the program such that it repeats until the user input a non-positive number.
More information on Euclidean Algorithm:
 Visible Euclidean Algorithm:
http://www.math.umn.edu/~garrett/crypto/a01/Euclid.html
 Euclidean Algorithm and proof at MathWorld:
http://mathworld.wolfram.com/EuclideanAlgorithm.html
 Simple explanation of Euclidean Algorithm:
http://www.cut-the-knot.org/blue/Euclid.shtml
 Information of Euclidean Algorithm at Wikipedia:
http://en.wikipedia.org/wiki/Euclidean_algorithm
http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
[05.12.01] CLSMSS/0506/S4CIT/Ex02
P. 1/1
Download