因式分解(递推 递归) SDUT

版权声明:本人原创文章若需转载请标明出处和作者!沙 https://blog.csdn.net/weixin_44143702/article/details/87624550

因式分解

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

将大于1的自然数N进行因式分解,满足N=a1*a2*a3…*am。
编一程序,对任意的自然数N(1< N<=2,000,000,000),求N的所有形式不同的因式分解方案总数。如N=12,共有8种分解方案,他们分别是: 
12=12 
12=6*2 
12=4*3 
12=3*4 
12=3*2*2 
12=2*6 
12=2*3*2 
12=2*2*3 

Input

输入只有一行,一个整数N。

Output

输出只有一行,一个整数表示自然数N的因式分解方案总数。

Sample Input

12

Sample Output

8

解题思路:

用N除以 2 一直到 n,结果不为整则加 1 再除;

若为整,用商代替 n,从 2 开始除一直到 n 

#include <stdio.h>
#include <stdlib.h>
void f(int);
int sum = 1;///此处的1也很重要,因为 n 本身就是自己的因式,即 n = 1 * n
int main()
{
    int n;
    scanf("%d", &n);
    f(n);
    printf("%d\n", sum);
    return 0;
}
void f(int n)
{
    int i;
    for(i = 2; i < n ;i++)///此处不能写 i <= n !!!否则会多出很多结果
    {///若写等号,则每次进入for循环都会进入if,因为总会有 i = n
    ///此处 i 也不能写成 1 ,因为 n % 1 = 0 永远成立,会无限进入if并进入递归函数,导致死机
        if(n % i == 0)
        {
            f(n / i);
            sum++;
        }
    }
}

其他人的解法: 

1. https://blog.csdn.net/jyl1159131237/article/details/78879485

猜你喜欢

转载自blog.csdn.net/weixin_44143702/article/details/87624550
今日推荐