• 1200:分解因数


    描述

    给出一个正整数a,要求分解成若干个正整数的乘积,即a = a1 * a2 * a3 * ... * an,并且1 < a1 <= a2 <= a3 <= ... <= an,问这样的分解的种数有多少。注意到a = a也是一种分解。

    输入

    第1行是测试数据的组数n,后面跟着n行输入。每组测试数据占1行,包括一个正整数a (1 < a < 32768)

    输出

    n行,每行输出对应一个输入。输出应是一个正整数,指明满足要求的分解的种数

     

    写法一:直接搜索,从a1搜素到an,满足条件则+1。

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 int x,ans;
     4 void dfs(int p,int k){ //p表示乘积,k表示当前的因子
     5     if(p==x){
     6         ans++;
     7         return;
     8     }
     9     for(int i=k;i<=x;i++){
    10         if(p*i>x)break;
    11         if(x%i==0)dfs(p*i,i);
    12     }
    13 }
    14 int main(){
    15     int n;
    16     scanf("%d",&n);
    17     while(n--){
    18         ans=0;
    19         scanf("%d",&x);
    20         dfs(1,2);
    21         printf("%d
    ",ans);
    22     }
    23     return 0;
    24 }

    写法二:

     1 #include <iostream>  
     2 #include <cstdio>  
     3 #include <cstdlib>  
     4 #include <cmath>  
     5 #include <cstring>  
     6 #include <string>  
     7 #include <queue>  
     8 #include <algorithm>  
     9 using namespace std;  
    10 
    11 int sum;  
    12 
    13 void count(int a,int b)  
    14 {  
    15     for(int i=a;i<b;i++)  
    16     {  
    17         if(b%i==0&&i<=b/i)  
    18         {  
    19             sum++;  
    20             count(i,b/i);//递归计算  
    21         }  
    22         if(i>b/i) break;  
    23     }  
    24 }  
    25 int main()  
    26 {  
    27     int n;  
    28     int a;  
    29 
    30     cin >> n;  
    31     while(n)  
    32     {  
    33         sum = 1;  
    34         cin >> a;  
    35         count(2,a);  
    36         cout<<sum<<endl;  
    37         n--;  
    38     }  
    39     return 0;  
    40 }  

    墙裂建议把以上两个代码模拟一遍

  • 相关阅读:
    二进制位运算
    Leetcode 373. Find K Pairs with Smallest Sums
    priority_queue的用法
    Leetcode 110. Balanced Binary Tree
    Leetcode 104. Maximum Depth of Binary Tree
    Leetcode 111. Minimum Depth of Binary Tree
    Leetcode 64. Minimum Path Sum
    Leetcode 63. Unique Paths II
    经典的递归练习
    案例:java中的基本排序
  • 原文地址:https://www.cnblogs.com/tflsnoi/p/9670348.html
Copyright © 2020-2023  润新知