0% found this document useful (0 votes)
18 views4 pages

Cs Assignment

The document provides two ways to calculate the greatest common divisor (GCD) of two numbers in C++. The first method uses iteration in a for loop to find the largest integer that divides both numbers. The second method uses recursion by checking base cases and recursively calling the gcd function to reduce the numbers until they are equal.

Uploaded by

anon_626239334
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views4 pages

Cs Assignment

The document provides two ways to calculate the greatest common divisor (GCD) of two numbers in C++. The first method uses iteration in a for loop to find the largest integer that divides both numbers. The second method uses recursion by checking base cases and recursively calling the gcd function to reduce the numbers until they are equal.

Uploaded by

anon_626239334
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Q12. . WAP to calculate the GCD of two numbers.

1. Using iteration.

#include<iostream>

using namespace std;

int main() {

int first_number;

cout<<"Enter First Number : ";cin>>first_number;

int second_number;

cout<<"Enter Second Number: ";cin>>second_number;

int gcd;

for(int i=1;i<=first_number&&i<=second_number;i++)

if(first_number%i==0 && second_number%i == 0 )

{
gcd=i;

cout<<"Greatest Common Divison (GCD):"<<gcd<<endl;

return 0;

Output :

2. Using recursion.

#include<iostream>
using namespace std;

int gcd(int a, int b) {

if (a == 0 || b == 0)

return 0;

else if (a == b)

return a;

else if (a > b)

return gcd(a-b, b);

else return gcd(a, b-a);

int main() {

int a, b;

cout<<"enter two numbers:"<<" ";

cin>>a>>b;

cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b);

return 0;

Output :

You might also like