Spoj DIVSUM2 - Divisor Summation (Hard) Solution
Problem Link : https://www.spoj.com/problems/DIVSUM2/
Algorithm Link : https://cp-algorithms.com/algebra/divisors.html
Solution in C++:
- ///La ilaha illellahu muhammadur rasulullah
- ///******Bismillahir-Rahmanir-Rahim******///
- ///Abul Hasnat Tonmoy
- ///Department of CSE,23rd batch
- ///Islamic University,Bangladesh
- #include <bits/stdc++.h>
- using namespace std;
- #define mx 100000009
- #define ll long long
- bitset<mx>isprime;
- vector<ll>prime;
- void sieve()
- {
- isprime.set();
- isprime[0]=false;
- isprime[1]=false;
- for(int i=0; i<mx; i++)
- {
- if(isprime[i])
- {
- prime.push_back(i);
- for(int j=i*2; j<mx; j+=i)
- isprime[j]=false;
- }
- }
- }
- ll power(ll p,ll q)
- {
- if(q==0)
- return 1;
- if(q==1)
- return p;
- ll ans=1;
- while(q--)
- ans*=p;
- return ans;
- }
- ll solution(ll n)
- {
- ll sum=1,cnt;
- for(int i=0; i<prime.size()&&i*i<n; i++)
- {
- if(n%prime[i]==0)
- {
- cnt=0;
- while(n%prime[i]==0)
- {
- cnt++;
- n/=prime[i];
- }
- sum*=(power(prime[i],cnt+1)-1)/(prime[i]-1);
- }
- }
- if(n>1)
- {
- sum*=n+1;/// for prime number
- }
- return sum;
- }
- int main()
- {
- long long n,a,b,count,i,p,t,cn,sum;
- sieve();
- cin>>t;
- while(t--)
- {
- cin>>n;
- cout<<solution(n)-n<<endl;
- }
- }
No comments