递归求质因数

编写递归函数,输入一个自然数将其表示成质因数乘积的形式

例:

输入140

输出 140 = 2 * 2 * 5 * 7 或 140 = 7 * 5 * 2 * 2

#include<stdio.h>
//#include<string>

void A(int x)
{
    if (x == 1)
        return;
    int i = 2;
    while(x % i != 0)
        i++;
    A(x/i);
    printf("%d\n",i);
}

void B(int x, int i){
    if (x == 1)
            return;
    while(x % i == 0){
            printf("%d\n",i);
            x = x / i;
    }
    B(x, ++i);
}

int main(int argc, char *argv[])
{
    int n;
    scanf("%d",&n);
    A(n);               //降序打印
    B(n,2);             //升序打印
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Liangren_/article/details/83446725