有人可以帮助纠正我的算法吗?我已经在一些数字上测试了它,并没有输出完整的因子分解.对于具有大量因素的数字,它只是完全失败.
int num = 20;
for(int i = 2; i <= num; i++)
{
if(num%i == 0)
{
cout << i << endl;
cout << num << endl;
num = num/i;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:提供的两个答案不起作用,仍然没有得到完整的结果.
EDIT2:除数VS因子
ste*_*fan 12
从你对@的评论判断Luchian Grigore
,你会将除数与(素数)因子分解混淆.数字的除数num % i == 0
都是真的数字.分解意味着num
通过较小数字的乘积来表示.如果您想要分解的唯一性,通常使用素数分解.
要获得所有除数,你的代码应该是
for ( int i = 1; i <= num; ++i ) // note that 1 and num are both trivially divisors of num
{
if ( num % i == 0 ) // only check for divisibility
{
std::cout << i << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
获得(素数)因子分解,它是
for ( int i = 2; i <= num; ++i )
{
while ( num % i == 0 ) // check for divisibility
{
num /= i;
std::cout << i << std::endl;
}
// at this point, i cannot be a divisor of the (possibly modified) num.
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14935 次 |
最近记录: |