0

How to make this more time efficient??

#include <iostream> #include<math.h> using namespace std; int lcm(int a,int b) { for(int i=max(a,b) ; ;i++) { if(i%a==0 && i%b==0) return i; } } int main() { // your code goes here int n; cin>>n; int a[n]; for(int i=0 ;i<n ;i++) cin>>a[i]; int maxa=0; for(int i= 0 ; i<n ;i++) { for(int j=i+1 ;j<n ;j++) { maxa=max(maxa,lcm(a[i],a[j])); } } cout<<maxa; return 0; }

28th Apr 2020, 5:29 PM
Shubhank Kulshreshtha
Shubhank Kulshreshtha - avatar
1 Resposta
0
Just notice that lcm of a ant b can be found more efficiently as a result of a * b / greatest common factor as like code below int gcf(int n1, int n2) {   int div;   if (n1 == n2)  return n1;   int d = n1 - n2;   if (d < 0) {     d = -d;  div = gcf(n1, d);   } else     div = gcf(n2, d);    return div; } lcm(int a, int b){ return a * b / gcf(a, b); }
29th Apr 2020, 10:30 PM
K.islo
K.islo - avatar