I know how to write the GCD for one, two, three, four, and etc, numbers. But I cannot seem to find a way to write a code that does it for 'n' numbers.
That is, the user inputs a number 'n', which determines the size of a dynamic array. Then they are prompted to input the values for each of the elements in the array that will constitute the numbers the program is to find the GCD for.
This records the array:
1 2 3 4 5 6 7 8 9
|
for (int count = 0; count < n; count++)
{
cout << "Enter the numbers you wish to find the GCD for, for term" << count << ": ";
cin >> GCD_n[count];
}
|
Here is a code for finding GCD of three numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
cout << "This program finds the greatest common divisor of three numbers. \n\n"
<< "Enter the first number: \n";
cin >> a;
cout << "Enter the second number: \n";
cin >> b;
cout << "Enter the third number: \n";
cin >> c;
for (int count = 1; count <= a && count <= b && count <= c; count++)
{
if (a%count == 0 && b%count == 0 && c%count == 0)
{
gcd = count;
}
}
cout << "Greatest Common Divisor: " << gcd << endl;
|
I have no idea how to proceed coding a program that finds the GCD of 'n' terms. Anyone know how to proceed? I have tried for hours and couldn't think of something. My knowledge of C++ is still at a beginner's stage, so I am hoping someone can help me here.
GCD_n[n] is the array that contains the numbers for which we need to determine the GCD for.
My main problem is with writing a code that tests the elements of the array containing the list of numbers in GCD_n[n], all at the same time, such that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
int n;
cout << "This program finds the greatest common divisor of n numbers. \n\n"
<< "What is the total amount of numbers you want to find the GCD for? \n";
cin >> n;
int*GCD_n = new int [n];
for(int i=0; i < n; i++)
{
if (GCD_n[0]%i==0 && GCD_n[1]%i==0 && GCD_n[2]%i==0 ... && GCD_n[n]%i==0 ) // I don't know how to write this part.
gcd = i;
}
|