找出数字的因素。得不到准确的结果 [英] Finding factors of a number. Not getting accurate results

查看:93
本文介绍了找出数字的因素。得不到准确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助更正我的算法吗?我已经测试了几个数字,它不输出完整的因式分解。对于具有大量因素的数字,它完全失败。

Can someone help correct my algorithm? I've tested it on a few numbers, and it doesn't output the complete factorization. For numbers with a large number of factors, it just completely fails.

int num = 20;

for(int i = 2; i <= num; i++)
{
    if(num%i == 0)
    {
        cout << i << endl;
        cout << num << endl;
        num = num/i;    
    }
}

编辑:提供的两个答案没有工作,仍然未获得完整结果。

The two answers provided did not work, still not getting full results.

EDIT2:除数与因子

Divisors VS Factors

推荐答案

从你对@ Luchian Grigore 的评论中,你会对因子(素数)因式分解产生混淆。数字的除数是 num%i == 0 为真的所有数字。因式分解意味着通过较小数字的乘积获得 num 的表示。

Judging from you comment to @Luchian Grigore, you're confusing divisors with (prime) factorization. Divisors of a number are all numbers for which num % i == 0 is true. Factorization means getting a representation of num by a product of smaller numbers. If you want uniqueness of factorization, you usually use prime factorization.

要获取所有的除数,你的代码应该是

To get all the divisors your code should be

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;
    }
}

p>

to get the (prime) factorization, it's

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.
}

这篇关于找出数字的因素。得不到准确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆