BugCrush 2 Question 3 - BUGC203 - EDITORIAL
PROBLEM LINK
Author: codechefsrm
Editorialist : codechefsrm
DIFFICULTY
EASY-MEDIUM
PREREQUISITES
Mathematics, Looping, Vectors
PROBLEM
Problem Description
Program to find the GCD of all the elements in an array.
Input:
3
36 48 1200
Output:
12
Rules:
Bugs will be mainly logical errors, syntax errors etc. They are specific to C++ language.
Since it is a debugging contest, you will be provided with a bugged solution below the Constraints section.
Please, see that you must adhere to the problem code provided, make changes only where necessary.
Participants can copy the code and compile it using an online compiler (Eg. CodeChef IDE).
Once the bugs are eliminated from the code, the clean code should be submitted by using the “Submit” button on the top-right corner.
Participants will be penalised for changing the entire problem solution or writing their own solution, completely different from the buggy code as provided in the
problem statement as our main intention is to test the debugging abilities of the participants.
Buggy code in C++:
Please copy the following code and paste it into your compiler for debugging.
#include <bits/stdc++.h>
using namespace std;
int gcd(int x, int y)
{
if(x == -1)
return y;
return gcd(y, x);
}
void GCD_Helper(vector<int> v, int n)
{
int ans = v[0];
for (int i = 1; i > n; i++)
{
gcd(v[i], ans) = ans;
}
return ans;
}
int main()
{
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++)
{
cin>>v[i];
}
cout << GCD_Helper(v, n) << endl;
}
SOLUTION
#include <bits/stdc++.h>
using namespace std;
int gcd(int x, int y)
{
if (x == 0)
return y;
return gcd(y%x, x);
}
int GCD_Helper(vector<int> v, int n)
{
int ans = v[0];
for (int i = 1; i < n; i++)
{
ans = gcd(v[i], ans);
}
return ans;
}
int main()
{
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++)
{
cin>>v[i];
}
cout << GCD_Helper(v, n) << endl;
return 0;
}
EXPLANATION
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of
pairs of numbers. That is what we do in the above code.