Saturday, 30 August 2014

Simple Algorithms |GCD and Leap year


Simple Algorithms

Simple GCD Algorithms

1-For smaller numbers we can use
      a- Suppose there are 2 nos, a,b . Smaller one is b.
      b-Choose a Var K and run it in decreasing order from b to 1
      c-In each iteration check whether it divides both a and b . If it does then stop and print ,exit.
 This is a very simple way of doing it and is very expensive when the numbers are large .





2-The other may be to use the funda of Euclid's GCD .
    i.e gcd (a,b)=gcd (b,a %b)  . b being smaller of a and b .Run till the mod part becomes zero .

  Flowchart :





GCD using recursion:


#include <stdio.h>
int gcd(int a , int b){
    //assumes a>b
   if (b==0) return a;
  return gcd(b,a%b);
}

int main()
{  int a,b,g;
   scanf("%d",&a);
   scanf("%d",&b);
   if (a<b)   {swap(a,b);}
  g=gcd(a,b)


}

------------------------------------------------------------------------------------------------

   The logic of leap years







++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++