2520是一个可以由每一个号码,没有任何剩余被划分为1〜10的最小数目。
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
这是最小正数,它是所有数字的整除从1至20个
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
我的解决办法:
#include<stdio.h> int gcd(int m, int n); int lcm(int a, int b); int main() { int x=1, i; for(i=1; i<20; i++) { x=lcm(x, i+1); } printf("The answer is:\t%d", x); return 0; } int gcd(int m, int n) { while(m!=n) { if(m>n) m=m-n; else n=n-m; } return m; } int lcm(int a, int b) { return ((a*b)/gcd(a, b)); }请告诉我在哪里错了?它显示在运行只空白屏幕。
Please tell where I am wrong? It shows only blank screen on running.
推荐答案如果有,应该只有一个,你从这个练习中吸取教训,使这样的:中,你做你的乘法和除法事项的顺序
If there should be only one lesson that you learn from this exercise, make it this: the order in which you do your multiplications and divisions matters.
即使没有在数学关系,往往在重要的程序。例如,在数学有GCD 之间没有差异(A * B)/(A,B)和 A / GCD(A,B) * b ;在你的程序中,它将使传递和失败之间的差别。
Even if it does not matter in mathematics, it often matters in your program. For example, in math there is no difference between (a*b)/gcd(a, b) and a/gcd(a, b)*b; In your program, it would make the difference between passing and failing.
(P.S当然你需要修复的bug在你的逻辑,太:你不应该乘以 X 通过LCM)。
(P.S. of course you need to fix the bug in your logic, too: you should not be multiplying x by lcm).
修改
要理解为什么为了使得这里的区别,考虑计算 LCM 232792560 和 20 。 232792560 是 20 整除,所以它是 LCM 。然而,当你计算 232792560 * 20 ,你会得到一个溢出;然后通过 20 分裂,但你没有得到 232792560 回来了。
To understand why the order makes the difference here, consider calculating lcm of 232792560 and 20. 232792560 is divisible by 20, so it is the lcm. However, when you calculate 232792560*20, you get an overflow; then you divide by 20, but you do not get 232792560 back.
由于除数为 GCD(A,B),你可以乘以之前划分出来 A 的 b 没有整数除法截断结果。这是经验丰富的小把戏程序员不假思索使用可以节省你的调试时间。
Since the divisor is gcd(a,b), you can divide it out of a before multiplying by b without truncating the result by integer division. This little trick that experienced programmers use without thinking can save you hours of debugging.
更多推荐
项目欧拉5
发布评论