(杭电1019 最大公约数) Least Common Multiple
least common multiple
time limit: 2000/1000 ms (java/others) memory limit: 65536/32768 k (java/others)total submission(s): 64855 accepted submission(s): 24737
problem description
the least common multiple (lcm) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. for example, the lcm of 5, 7 and 15 is 105.
input
input will consist of multiple problem instances. the first line of the input will contain a single integer indicating the number of problem instances. each instance will consist of a single line of the form m n1 n2 n3 ... nm where m is the number of integers in the set and n1 ... nm are the integers. all integers will be positive and lie within the range of a 32-bit integer.
output
for each problem instance, output a single line containing the corresponding lcm. all results will lie in the range of a 32-bit integer.
sample input
2 3 5 7 15 6 4 10296 936 1287 792 1
sample output
105 10296
这道水题连续提交五次,第六次才ac。。。。。。(我真是菜,最近做做的题有点自闭)
这是是我多次修改仍然不ac的题解(测试样例全过自己测了几个也没问题,很绝望)
#include <stdio.h> #include <math.h> int main() { int t,temp; scanf("%d",&t); for(int i=1; i <= t; i++) { int n; scanf("%d",&n); for(int j=1; j <= n ; j++) { int num; scanf("%d",&num); if(j == 1) { temp=num; continue; } int max; if(temp > num) max=num; else max=temp; for( ; max >= 1; max--) if(temp%max == 0&&num%max == 0) break; temp=temp*num/max; } printf("%d\n",temp); } return 0; }
最后有dalao指点,把求公因数的方法改成辗转相乘法并用函数嵌套终于ac 无奈绝望╮(╯﹏╰)╭ 关于辗转相除法求最大公因数,举个栗子: a=6, b=4; 第一步 a=a%b=6%4=2; 第二步 b=4; 第三步 a%b=2%4=0,此时a == 0,b=(上一步)a; 此时b就是最大公因数; (算了上详细讲解链接 )
以下为正确代码
#include <stdio.h> #include <math.h> int gcd(int a,int b){ //辗转相除法 if(b == 0) return a; return gcd(b,a%b); } int lcm(int a,int b) { return a/gcd(a,b)*b; //把函数打包 } int main() { int t,temp,n; scanf("%d",&t); for(int i=1; i <= t; i++) { scanf("%d",&n); int temp = 1; for(int j=1; j <= n ; j++) { int num; scanf("%d",&num); temp = lcm(temp,num); } printf("%d\n",temp); } return 0; }
上一篇: 3dsmax图纸模型怎么展贴图uv?