u wont be able to store lcm of array in any datatype since there can conditions where your denominator thats is gcd(a,b) equals 1 when these two are coprimes so u only keep on multiplying which which results in overflow
interger overflow.
suppose all no have gcd 1
But a[i] <= 10^4 and m <= 10^4 so max(lcm) = 10^8 which is within bounds of int and long long.
can u explain strip in a tree please
no
try to find the lcm prime numbers example (3,5,7,11) it will be the multiplication of all
and we have a lot of primes under 10^4 so it can easily exceed long long
Oh, I was too dumb. (10^4)^(10^4) would be the upper bound. Thank you for replying, by the way!!!
have a look at this
please take a look at this
Oops! That page doesnāt exist or is private.
#include
using namespace std;
long long int gcd(long long int a,long long int b)
{
if (b == 0)
{
return a;
}
return gcd(b, a % b);
}
long long int lcm(long long int a[],long long int n)
{
long long int ans = a[0];
for (long long int i = 1; i < n; i++)
{
ans = (a[i] * ans)/ (gcd(a[i], ans));
}
return ans;
}
int main() {
// your code goes here
int t;
cin>>t;
while(tā)
{
long long int n,m;
cin>>n>>m;
long long int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
long long int ans=lcm(a,n);
long long int max=ans;
long long int num=1;
for(long long int i=2;i<=m;i++)
{
long long int cur=(i*ans)/(gcd(i,ans));
if(cur>max)
{
max=cur;
num=i;
}
}
cout<<num<<endl;
}
return 0;
}
can you help to find the error in this?
LCM overflows range of int. Store prime factorization instead.
have a look here
look at this
here take a look at this please
beautiful approach,i must say!
Thank you, till now i got the point but now how will you find the smallest noā¦ I guess your approach should be traverse from 1 to m and for each no. find the prime factors and multiply with original lcm ???