hdu1215 七夕节---因子和
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1215
题目大意:
求N的因子和(不包括N本身)
解题思路:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<cmath> 6 #include<queue> 7 #include<stack> 8 #include<map> 9 #include<sstream> 10 #define Mem(a, b) memset(a, b, sizeof(a)) 11 using namespace std; 12 typedef long long ll; 13 const int INF = 1e9 + 7; 14 const int maxn = 1000000+10; 15 int prime[maxn]; 16 bool is_prime[maxn]; 17 int sieve(int n)//返回n以内素数的个数 18 { 19 int p = 0; 20 for(int i = 0; i <= n; i++)is_prime[i] = 1; 21 is_prime[0] = is_prime[1] = 0; 22 for(ll i = 2; i <= n; i++) 23 { 24 if(is_prime[i]) 25 { 26 prime[p++] = i; 27 for(ll j = i * i; j <= n; j += i)is_prime[j] = 0;//这里涉及i*i,必须使用long long 28 } 29 } 30 return p; 31 } 32 33 ll Divisors_num(ll n, int tot)//素数总数 34 { 35 ll ans = 1; 36 for(int i = 0; i < tot && prime[i] * prime[i] <= n; i++) 37 { 38 if(n % prime[i] == 0) 39 { 40 int cnt = 0; 41 while(n % prime[i] == 0) 42 { 43 cnt++; 44 n /= prime[i]; 45 } 46 ans *= (cnt + 1); 47 } 48 } 49 if(n > 1)ans *= 2; 50 return ans; 51 } 52 ll pow(ll a, ll b) 53 { 54 ll ans = 1; 55 while(b) 56 { 57 if(b & 1)ans = ans * a; 58 a *= a; 59 b /= 2; 60 } 61 return ans; 62 } 63 ll Divisors_sum(ll n, int tot) 64 { 65 ll ans = 1; 66 for(int i = 0; i < tot && prime[i] * prime[i] <= n; i++) 67 { 68 if(n % prime[i] == 0) 69 { 70 int cnt = 0; 71 while(n % prime[i] == 0) 72 { 73 cnt++; 74 n /= prime[i]; 75 } 76 ans = (pow(prime[i], cnt + 1) - 1) / (prime[i] - 1) * ans; 77 } 78 } 79 if(n > 1)ans *= (n + 1); 80 return ans; 81 } 82 int main() 83 { 84 int T, cases = 0; 85 int tot = sieve(1000000); 86 cin >> T; 87 while(T--) 88 { 89 ll n; 90 scanf("%lld", &n); 91 printf("%lld\n", Divisors_sum(n, tot) - n); 92 } 93 return 0; 94 }
越努力,越幸运