1到n,n个数的最小公倍数

来源:互联网 发布:怎么提高淘宝销售量 编辑:程序博客网 时间:2024/04/28 17:16
为什么1小时有60分钟,而不是100分钟呢?这是历史上的习惯导致。
但也并非纯粹的偶然:60是个优秀的数字,它的因子比较多。
事实上,它是1至6的每个数字的倍数。即1,2,3,4,5,6都是可以除尽60。

我们希望寻找到能除尽1至n的的每个数字的最小整数。

不要小看这个数字,它可能十分大,比如n=100, 则该数为:
69720375229712477164533808935312303556800

请编写程序,实现对用户输入的 n (n<100)求出1~n的最小公倍数。

例如:
用户输入:
6
程序输出:
60

用户输入:
10
程序输出:

2520

分析:

由于数可能很大,考虑用数组保存乘积。求1到n的最小公倍数,可以将1*2*3*...*n化简为最小公倍数相乘的形式。例如:1到6,1*2*3*4*5*6化简为,1*2*3*2*5*1 = 60;1到10,1*2*3*4*5*6*7*8*9*10化简为,1*2*3*2*5*1*7*2*3*1 = 2520。

代码如下:

#include <stdio.h>int temp[100];//保存n由哪些数相乘int a[50];//保存temp数组中各元素相乘的结果int fun(int x,int n);int main(){int n,i,j,count = 0,tag = 0;//(n < 100)scanf("%d",&n);for (i = 1; i <= n ; i++){temp[i - 1] = fun(i,i - 1);//将1*2*...*n化为最小公倍数相乘的形式}a[0] = 1;for (i = 0; i < n; i++)//保存乘积{if (temp[i] != 1){for (j = 0; j <= count || tag; j++)//temp数组中每个元素与a数组中已有元素相乘{int t = a[j];a[j] = (t * temp[i] + tag) % 10;tag =  (t * temp[i] + tag) / 10;if (j > count)//更新乘积的长度{count = j;}}}}for (i = count; i >= 0; i--)//输出结果{printf("%d",a[i]);}printf("\n");return 0;}int fun(int x,int n){for (int i = 0; i < n && x != 1 && temp[i] != 0; i++){if (x % temp[i] == 0){x /= temp[i];}}return x;}


原创粉丝点击