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

来源:互联网 发布:linux 解压到当前目录 编辑:程序博客网 时间:2024/05/17 15:40

题目描述

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

输入

输入包括一行。 
两个以空格分开的正整数。

输出

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

示例输入

6 8

示例输出

24 2

#include<stdio.h>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<m<=100)个正整数,求出m个数的最小公倍数。
 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<stdio.h>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<n;i++)            scanf("%d",&a[i]);            d=gcd(a[0],a[1]);            if(n>2)                for(i=2;i<n;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

 

23 5 7 156 4 10296 936 1287 792 1
 


 

Sample Output

 

10510296
 

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

#include<stdio.h>long LCM(long p1,long p2)//求最小公倍数{    long n1=p1,n2=p2;    if(n1<n2)    {        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 0
原创粉丝点击