找到给定整数的所有精确除数的算法 [英] Algorithm to find all the exact divisors of a given integer
本文介绍了找到给定整数的所有精确除数的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到一个数字的所有精确除数.目前我有这个:
I want to find all the exact divisors of a number. Currently I have this:
{
int n;
int i=2;
scanf("%d",&n);
while(i<=n/2)
{
if(n%i==0)
printf("%d,",i);
i++;
}
getch();
}
有什么办法可以改善吗?
Is there any way to improve it?
推荐答案
首先,你的代码应该具备i <= n/2
的条件,否则会漏掉其中一个因素,例如,如果 n=12,则不会打印 6.
First, your code should have the condition of i <= n/2
, otherwise it can miss one of the factors, for example 6 will not be printed if n=12.
运行循环到数字的平方根(即i <= sqrt(n)
)并打印i
和n/i
(都是 n 的倍数).
Run the loop to the square root of the number (ie. i <= sqrt(n)
) and print both i
and n/i
(both will be multiples of n).
{
int n;
int i=2;
scanf("%d",&n);
while(i <= sqrt(n))
{
if(n%i==0) {
printf("%d,",i);
if (i != (n / i)) {
printf("%d,",n/i);
}
}
i++;
}
getch();
}
注意:
- 对于一个完美的平方,平方根不会被打印两次,如@chepner 所建议的,在循环结束时对
i*i == n
进行额外的检查.李> - 如果您希望所有因子按升序将值存储在数组中,则在循环结束时对所有数字进行排序并显示.
这篇关于找到给定整数的所有精确除数的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文