1. 程式人生 > 實用技巧 >5.約數個數 6.約數之和 約數

5.約數個數 6.約數之和 約數

如何求一個數約數的個數以及如何求一個數約數的和:基於算數基本定理

題目一:約數個數

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int mod = 1e9 + 7;
 5 int main() {
 6     int n;
 7     cin >> n;
 8     unordered_map<int, int> primes; //儲存所有底數和指數
 9     while (n--) {
10         int x;
11 cin >> x; 12 for (int i = 2; i <= x / i; i++) { 13 while (x % i == 0) { 14 x /= i; 15 primes[i]++; 16 } 17 } 18 if (x > 1) { 19 primes[x]++; 20 } 21 } 22 ll res = 1; 23 //
不用c++11新特性的auto的unordered_map的遍歷方式 24 for (unordered_map<int, int>::iterator it = primes.begin(); it != primes.end(); it++) { 25 res = res * (it -> second + 1) % mod; 26 } 27 cout << res << endl; 28 return 0; 29 }

題目二:約數之和

 1 #include <bits/stdc++.h>
 2
using namespace std; 3 typedef long long ll; 4 const int mod = 1e9 + 7; 5 int main() { 6 int n; 7 cin >> n; 8 unordered_map<int, int> primes; 9 while (n--) { 10 int x; 11 cin >> x; 12 for (int i = 2; i <= x / i; i++) { 13 while (x % i == 0) { 14 x /= i; 15 primes[i]++; 16 } 17 } 18 if (x > 1) { 19 primes[x]++; 20 } 21 } 22 ll res = 1; 23 for (unordered_map<int, int>::iterator it = primes.begin(); it != primes.end(); it++) { 24 int p = it -> first, a = it -> second; 25 //p是底數,a是指數 26 ll t = 1; //t是當前這個數p的0 ~ a1次方相加 27 while (a--) { 28 t = (t * p + 1) % mod; 29 } 30 res = res * t % mod; 31 } 32 cout << res << endl; 33 return 0; 34 }