算法找到一个给定的整数的所有确切的除数 [英] 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?
推荐答案
首先,你的code应具备的条件为 I&LT; = N / 2
,否则它可以错过的因素之一,对于实施例6将不被打印的情况下的n = 12
First, your code should have the condition as i <= n/2
, otherwise it can miss one of the factors , for example 6 will not be printed in case of n=12.
运行循环,直到数sqaure根,即:的sqrt(N)
和打印两个我
和 N / I
(都将为n的倍数)。
Run the loop till sqaure root of the number ie: 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();
}
请注意:
- 对于一个完美的sqaure,这样的平方根不能打印了两次,额外进行检查,在循环的末尾
I * I ==ñ
的建议通过@chepner。 - 如果您希望所有的因素,按升序排列,将它们存储在一个数组,在循环结束时,把所有的数字和显示。
- For a perfect sqaure , so that the square root is not printed twice , the additional checking is done at the end of loop for
i*i == n
as suggested by @chepner. - If you want all the factors in ascending order , store them in an array, at the end of the loop , sort all the numbers and display.
这篇关于算法找到一个给定的整数的所有确切的除数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文