Maximize LCM lunchtime,my code giving WA

my code is giving wrong answer but all test cases are passing, please help -,
here is my code :-1
//lunchtime division 2 p.3

#include<bits/stdc++.h>
using namespace std;
#define vi vector
#define ll unsigned long long int
#define pp long long int
#define pb push_back
#define mp make_pair
#define eb emplace_back

ll gcd(ll a, ll b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}

ll findlcm(ll arr[], ll n)
{
// Initialize result
ll ans = arr[0];
for (ll i = 1; i < n; i++)
ans = (((arr[i] * ans)) /
(gcd(arr[i], ans)));

return ans; 

}

int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll t;
cin>>t;
while(t–)
{
ll n,m;
cin>>n>>m;
ll a[n+1];
ll ans=0;
for(ll i=0;i<n;i++)
{
cin>>a[i];
}
unordered_map<ll,ll>mt;
for(ll j=1;j<=m;j++)
{
a[n]=j;
ll x=findlcm(a,n+1);
if(x>=ans)
{
ans=x;
}
mt[j]=x;
}
ll key=0;
for(ll i=1;i<=m;i++)
{
if(mt[i]==ans)
{
key=i;
break;
}
}
cout<<key<<endl;
}
return 0;
}

you can’t store lcm in integer or even in long long,
use factorization method
check the other link in the discuss

2 Likes

Consider the case when all 10^4 numbers are maximum distinct prime numbers. Then the lcm would be multiplication of all of them. In order to store lcm of prime numbers till 10^4, you need at least a data type that can store a number of order of 10^(10^4) at least. So, you cannot do that, even __int128 would overflow. Try using factorization method instead. Then you need to store only corresponding powers to each prime numbers instead of multiplying them all.

1 Like