gpt4 book ai didi

c - 找出多个数的最小公倍数

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:12 24 4
gpt4 key购买 nike

这个程序的目标是找出能被 1 到 20 整除而没有余数的最小数。该代码正在运行,但需要 33 秒。我可以改进它以使其更快吗?怎么办?

#include <stdio.h>

int main(){
int number = 19, i, k;

label:
number++;
k = 0;
for (i = 1; i <= 20; i++){
if (number%i == 0){
k++;
}
}

if (k != 20){
goto label;
}

printf("%d\n", number);
return 0;
}

最佳答案

#include <stdio.h>


/* GCD returns the greatest common divisor of a and b (which must be non-zero).

This algorithm comes from Euclid, Elements, circa 300 BCE, book (chapter)
VII, propositions 1 and 2.
*/
static unsigned GCD(unsigned a, unsigned b)
{
while (0 < b)
{
unsigned c = a % b;
a = b;
b = c;
}

return a;
}


int main(void)
{
static const unsigned Limit = 20;

unsigned LCM = 1;

/* Update LCM to the least common multiple of the LCM so far and the next
i. The least common multiple is obtained by multiplying the numbers
and removing the duplicated common factors by dividing by the GCD.
*/
for (unsigned i = 1; i <= Limit; ++i)
LCM *= i / GCD(LCM, i);

printf("The least common multiple of numbers from 1 to %u is %u.\n",
Limit, LCM);
}

关于c - 找出多个数的最小公倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56265466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com