C语言实验 最小公倍数和最大公约数,C语言实验——最小公倍数和最大公约数

题目描述

从键盘输入两个正整数,求这两个正整数的最小公倍数和最大公约数,并输出。

输入

输入包括一行。

两个以空格分开的正整数。

输出

两个整数的最小公倍数和最大公约数。

示例输入

6 8

示例输出

24 2

#include

void main()

{

int a,b,n,m,r;

scanf("%d %d",&m,&n);

a=m*n;

if(n>m)

{r=n;n=m;m=r;}

while(n!=0)

{

r=m%n;

m=n;

n=r;

}b=a/m;

printf("%d %d\n",b,m);

}

多个数求最下公倍数,开始看了网上的一个公式自己敲出来怎么也不对后来问了zhengnanlee才明白呢个公式不对,

其实就是把一串数字前两个求最小公倍数再依次往后求就可以

问题描述:

给你n组测试数据,每组测试数据有m(0

Input: 输入n,随后有n行,每行开头输入m,m之后有m个正整数,相邻数之间用空格隔开。

Output: 每行输出一个数(该数在int范围内,同时,数前面加个“Case 1: ”,表示第几个Case,如“Case 1: 6”),相邻两组结果之间有一个空行,输出完最后一个结果后,再加一个空行,具体形式见样例。

答题说明:

输入样例:

3

2 2 3

3 2 5 7

5 1 2 3 4 5

输出样例:

Case 1: 6

Case 2: 70

Case 3: 60

#include

int gcd(int a,int b)

{

int d,e,c;

d=a;

e=b;

while(a!=0)

{

c=b%a;

b=a;

a=c;

}

return d*e/b;

}

int main()

{

int m,n,i,d,a[101],Case=1;

scanf("%d",&m);

while(m--)

{

scanf("%d",&n);

for(i=0;i

scanf("%d",&a[i]);

d=gcd(a[0],a[1]);

if(n>2)

for(i=2;i

d=gcd(d,a[i]);

printf("Case %d: %d\n",Case++,d);

}

return 0;

}

Least Common Multiple

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

有的没排序也对了但是这是最完整的代码

#include

long LCM(long p1,long p2)//求最小公倍数

{

long n1=p1,n2=p2;

if(n1

{

long t=n1;

n1=n2;

n2=t;

}

long m=n1%n2;

while(m!=0)

{

n1=n2;

n2=m;

m=n1%n2;

}

return p1/n2*p2;//不容易溢出

}

int main()

{

long t,n;

scanf("%ld",&t);

while(t--)

{

long a=1,b=1;

scanf("%ld",&n);

while(n--)

{

scanf("%ld",&a);

b=LCM(a,b);

}

printf("%ld\n",b);

}

return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值