Wednesday, February 21, 2024

WAP to calculate GCD of 2 number (i) with recursion (ii) without recursion

 #include <iostream>

using namespace std;


class cl

{

private:

int n1,n2;

public:

void input()

{

cout<<"\nEnter 2 nunbers: ";

cin>>n1>>n2;

}

void gcd()


{

int g;

for(int i=1;i<=n1 && i<=n2;i++)

{

if(n1%i==0 && n2%i==0)

g=i;

}

cout<<"GCD= "<<g;

}

int gcd(int a, int b)

{

// Everything divides 0

if (a == 0)

return b;

if (b == 0)

return a;


// base case

if (a == b)

return a;


// a is greater

if (a > b)

return gcd(a-b, b);

return gcd(a, b-a);

}

};

int main()

{

cl ob;

int ch,m,n;



do

{

    cout<<"**GCD of 2 numbers**\n\n1.using Recursion \n2. Not using Recursion\n3.Exit";

cout<<"\n\nEnter ur Choice: ";

cin>>ch;

switch(ch)

{

case 1:

cout<<"\nEnter 2 numbers: ";

cin>>m>>n;

cout<<"GCD= "<<ob.gcd(m,n);

break;


case 2:

ob.input();

ob.gcd();

break;


case 3:

cout<<"\nEXIT";

break;


default:

cout<<"\nSorry! Invalid Choice";

}

}

while(ch!=3);

return 0;

}

No comments:

Post a Comment