Hackerrank Weekly challenges Week 8 - John and GCD list:
https://www.hackerrank.com/contests/w8/challenges/john-and-gcd-list
Hackerrank Weekly challenges Week 8 - John and GCD list solution: http://ideone.com/QZZxNC
#include <iostream>
#include <cstdio>
int gcd(int u, int v) {
if(u==v) return u;
if(u==0) return v;
if(v==0) return u;
if(~u&1) {
if(v&1) return gcd(u>>1, v);
return gcd(u>>1, v>>1)<<1;
}
if(~v&1) return gcd(u, v>>1);
if(u>v) return gcd((u-v)>>1, v);
return gcd((v-u)>>1, u);
}
int lcm(int u, int v) {
return u*v/gcd(u, v);
}
int main() {
int t, n, a[1005], b[1005];
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
for(int i=0; i<n; i++) scanf("%d", &a[i]);
b[0]=a[0];
for(int i=1; i<n; i++) b[i]=lcm(a[i-1], a[i]);
b[n]=a[n-1];
for(int i=0; i<=n; i++) printf("%d ", b[i]);
printf("\n");
}
return 0;
}
No comments:
Post a Comment