求N个数的最大公约数和最小公倍数。用C或C++或java或python语言实现程序解决问题。
代码如下:
#include "pch.h"
#include <iostream>
using namespace std;
int digui(int a,int b) { //定义返回两数最大公约数算法
a = (a > b) ? a : b;
if (a % b == 0)
{
return(b);
}
else return( b , a%b);
}
int zxgbs(int a, int b) { //定义返回两数最小公倍数算法
int temp;
temp = a > b ? a : b;
while (1) {
if ((temp) % b == 0)
break;
else temp = temp + a;
}
return(temp);
}
int main()
{
int i, c, n,d=0;
int t[100];
printf("请输入所计算值的数目n:");
scanf_s("%d", &n);
for (i = 0; i < n; i++)
{
printf("输入计算值:\n");
scanf_s("%d", &t[i]);
}
for (int m = 1; m < n; m++) //循环求出n数最大公约数
{
c = digui(t[0], t[m]);
c = c < t[0] ? c : t[0];
}
for (int m = 1; m < n; m++) { //循环求出n数最小公倍数
t[0] = zxgbs(t[0], t[m]);
}
d = t[0];
cout << "n数最大公约数为:" << c << endl;
cout << "n数最小公倍数为:" << d << endl;
}
两数最大公约数的扩展程序。