In: Computer Science
Write a C++ program for Euclids Algorithm that keeps track of the number of iterations (% & loop)
1. Euclid’s Algorithm An alternative of the Euclidean algorithm for finding greatest common divisors (GCD) is repeatedly performing the modulo operation on two numbers until the remainder is 0. Here is the pseudocode for find the GCD of two positive numbers a and b using the Euclidean algorithm :while b ≠ 0 temp = b b = a mod t a = t Create a program that asks the user for two positive integers. The program should validate that the input numbers are both positive and asks the user to reenter if needed. It then calculates the GCD using the Euclidean algorithm as described above, while keeping track of how many times the modulo operation is performed. The program outputs should include the GCD and the number of times for which the modulo operation is performed.
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments (read them for better understanding).
Images of the Code:
Note: If the below code is missing indentation please refer
code Images
Typed Code:
//including required headers
#include <iostream>
using namespace std;
int main()
{
// variable to store user input
int a,b;
// prompt for a Positive Number
cout << "Enter a Positive Number :";
// reading value from user
cin >> a;
// if input value is negative
while(a<0)
{
// prompt error message
cout << "Invalid input!\n";
// prompt for a Positive Number
cout << "Enter a Positive Number :";
// reading value from user
cin >> a;
}
// prompt for a Positive Number
cout << "Enter a Positive Number :";
// reading value from user
cin >> b;
// if input value is negative
while(b<0)
{
// prompt error message
cout << "Invalid input!\n";
// prompt for a Positive Number
cout << "Enter a Positive Number :";
// reading value from user
cin >> b;
}
// A variable to store modulo operation count
int Modulo_count=0;
// A variable to store loop running count
int loop_count=0;
// calculting GCD
// if b is non zero value
while(b!=0)
{
//storing b value in temp
int temp =b;
//performing Modulo operation
b= a%temp;
// changing a value to temp
a = temp;
// incrementing Modulo_count
Modulo_count++;
// incrementing loop_count
loop_count++;
}
//Printing GCD
cout << "GCD : "<<a << "\n";
//Printing Modulo count
cout << "Modulo operation is performed " <<
Modulo_count << " times\n";
//Printing Loop Count
cout << "Loop Count is "<< loop_count <<
"\n";
return 0;
}
//code ended here
Output:
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!