我的程序当前以升序输出正整数的质数分解。我试图弄清楚如何设置函数,以便它以降序输出数字。

例如,showFactors(100)当前输出“2 2 5 5”。

相反,我希望它输出“5 5 2 2”。

 10 // Void function "showFactors" that takes in an int "number" and another     int "factor", which is initialized to 2
 11 void showFactors(int number, int factor = 2)
 12 {
 13
 14   if (number<2) //returns nothing if number<2
 15   {
 16     return;
 17   }
 18   if (number%factor==0) //modulus function is used to get prime  factorization
 19   {
 20     cout<<factor<<" ";
 21     showFactors(number/factor, factor); //recursive call
 22   }
 23   else //if (number%factor != 0) //this modulus function is used in order to output factor !=2
 24   {
 25     showFactors(number, factor+1);
 26   }
 27 }

我觉得应该通过简单地重新排列cout调用的位置来解决问题,但是到目前为止我还没有运气。

编辑:是的,就像切换20和21行一样简单。

最佳答案

#include <iostream>
using namespace std;
void sf (int number,int factor=2)
{
    if (number<2)
        return;
    if (number%factor == 0)
    {
        sf (number/factor,factor);
        cout<<factor<<"\t";
    }
    else
        sf (number,factor+1);
}

int main ()
{
    sf (1729);
    cout<<"\n";

    return 0;
}

关于c++ - 使用递归的素数分解,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39607725/

10-12 01:51