Responsive Ads Here

Saturday 9 September 2017

Minimum sum of factors

problem id:--http://practice.geeksforgeeks.org/problems/minimum-sum-of-factors/0

In this problem we first calculate and store at least one prime factor of every number.
if the given number is prime number then just add 1 to it and that will be our required answer.
is the given number is not a prime then find the prime number by factor array . add it to sum and then divide that element by that prime factor .

code:--

#include <bits/stdc++.h>
#define gc() getchar()
using namespace std;
template <typename T> void scan(T &angka){
angka=0;char input=gc();T kali=1;
while(!(48<=input&&input<=57)){ if(input=='-') kali=-1;input=gc();}
while(48<=input&&input<=57) angka=(angka<<3)+(angka<<1)+input-48,input=gc();angka*=kali;
}

bool visit[(int)1e5+5];
int factor[(int)1e5+5];
vector<int> prime;
void magic()
{
int n=1e5+5;
for(int i=2;i<=n;++i)
{
if(!visit[i])
{
visit[i]=1;
factor[i]=i;
prime.push_back(i);
}
for(int j=0;j<prime.size() && i*prime[j]<=n;++j)
{
factor[i*prime[j]]=prime[j];
visit[i*prime[j]]=1;
}
}
}
int main()
{
magic();
int t;
scan(t);
while(t--)
{
int n;
scan(n);
if(n==1)
{
cout<<n<<'\n';
continue;
}
if(!n || factor[n]==n)
{
cout<<n+1<<'\n';
continue;
}
int sum=0;
while(n!=1)
{
sum+=factor[n];
n/=factor[n];
}
cout<<sum<<'\n';
}
return 0;
}

No comments:

Post a Comment