I am new to C++ and I have to optimise this code so that it gets executed within 1.5 secs for Input values upto 10^6. But this code takes 3.52 seconds for input 10^6 to get executed.
I had tried a lot and came up with this code.
#include <iostream>
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <iterator>
#include <utility>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
using namespace std;
cpp_int gcd(cpp_int a, cpp_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()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cpp_int t, ans;
std::cin >> t;
while (t-- > 0) {
cpp_int k;
std::cin >> k;
cpp_int limit = (2 * k) + 1;
ans = 0;
vector<cpp_int> g1;
for (int i = 1; i <= limit; ++i)
g1.push_back(k + (i * i));
for (int i = 0; i <= (2 * k) - 1; ++i) {
ans += gcd(g1[i], g1[i + 1]);
}
std::cout << ans << std::endl;
}
return 0;
}
Constraints --> 1 ≤ t ≤ 10^6 & 1 ≤ k ≤ 10^6