Tuesday, July 28, 2009

How can i write a c programme that calls a function Euclid's algorithm?

The Greatest Common Divisor (GCD) of two positive integers is the largest integer which can be divided evenly into both integers.


Problem 1: Given two integers A and B (assume that A %26gt; B) write a C program that calls a function called primitiveGCD( A,B) to calculate the GCD of two positive integers. This function uses a simple algorithm based on successive test of all numbers less than or equal to B, in order to find the greatest common divisor.


The pseudo-algorithm for implementing the function is as follows:


1. Require that A ≥ 0 and B ≥ 0


2. If A %26lt; B swap A and B


3. Set g = B


4. While g does not simultaneously divide A and B let g=g-1


5. Return g


Problem 2: Similar to the problem 1 chapter 5 page 338 of the textbook.


Euclide’s algorithm for calculating the GCD of two positive integers is based on the following observation:


Given two nonnegative integers A and B where (A %26gt; B), then the greatest common divisor of A and B is also the common divisor of A%B and B.

How can i write a c programme that calls a function Euclid's algorithm?
int primitiveGCD(int A, int B){


int g;


if (A %26lt; 0 || B %26lt; 0 ) return -1; /*error*/


g = B;


if (A %26lt; B){B = A; A = g; g = B;}


/* if g is not a factor of either it will return true value and it will continue looping */


while(A%g || B%g)g--;





return g;


}





You can at least write the program. Cheating doesn't help you learn.


No comments:

Post a Comment