首页 > 编程 > Java > 正文

hdu2028java-Lowest Common Multiple Plus

2019-11-08 02:03:42
字体:
来源:转载
供稿:网友

题目

PRoblem Description 求n个数的最小公倍数。

Input 输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数。

Output 为每组测试数据输出它们的最小公倍数,每个测试实例的输出占一行。你可以假设最后的输出是一个32位的整数。

Sample Input

2 4 6 3 2 5 7

Sample Output

12 70

思路

先求最大公约数;再求两数的最小公倍数,先除后乘,避免int越界

代码

或是

import java.util.*;public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int s=1; int n=sc.nextInt(); int[]a=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); s=s/LCM(s,a[i])*a[i]; } System.out.println(s); } } static int LCM(int a,int b){ int x; while(a%b!=0){ x=b; b=a%b; a=x; } return b; }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表