【发布时间】:2022-01-02 05:36:34
【问题描述】:
我需要编写一个函数,将 n 作为参数,并返回(作为字符串)最小的可能数字,而不是从 1 到 n 的所有数字。 例如,如果 n=4,则函数将返回 12,因为 12/4 12/3 12/2 12/1 是整数。
我已经编写了一个函数,当数字小于 19 时可以正常工作。超过 19 时,计算时间会变得更长。 有人可以给我一个提示,如何改进这个函数的机制以更快地完成它
public static string Smallest(int n)
{
int good = 0;//will hold number of times we got divide with no remianders
int num = n;//smallest possible number is n
while (true)
{
good = 0;
for (int i=n; i>=1; i--)
{
if (num % i ==0) good++;//meaning we got zero remainder for the divide
if (good == n) return num.ToString();//num of times we got zero remainders == n.
}
num++;
}
}
【问题讨论】:
-
首先,我很确定有一种在阴影中等待的体验,关于数字的某种模式。但是,鉴于您现有的代码,您应该尝试反转您的内部循环,以便如果您发现它没有划分的数字,请尽早中断,不要检查所有其他数字。
-
StackOverflow,从技术上讲,适用于损坏的代码 - 对于需要改进的工作代码,它更适合在 codereview.stackexchange 上询问。只是好奇,不是 4x3=12 和 5x4x3=60 作为候选开始等吗?
-
有一些示例代码on www.geeksforgeeks.org 可能会有所帮助。
-
这称为最低公倍数或 LCM。互联网上有很多关于它的东西。