经典算法 整数因子分解问题
Problem Description
大于 1 的正整数 n
可以分解为:
n = x₁ * x₂ * ... * xₘ
其中每个 xᵢ
是正整数,x₁ * x₂ * ... * xₘ = 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
,满足:
1 ≤ n ≤ 2,000,000,000
Output
输出 n
的不同分解式数量。
Sample Input
12
Sample Output
8
c++代码
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
typedef long long ll;
unordered_map<ll, ll> mp;
ll dfs(ll x) {
if (x == 1) return 1;
if (mp.find(x) != mp.end()) return mp[x];
ll ans = 1;
for (ll i = 2; i <= sqrt(x); i++) {
if (x % i == 0) {
ans += dfs(i);
if (x / i != i) ans += dfs(x / i);
}
}
mp[x] = ans;
return ans;
}
int main() {
ll n;
cin >> n;
cout << dfs(n);
return 0;
}//by wqs