项目欧拉5

编程入门 行业动态 更新时间:2024-10-20 04:08:26
本文介绍了项目欧拉5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

本文发布于:2023-11-29 20:41:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647571.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:欧拉   项目

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!