problem link-click here
This problem is easy to implement if you can understand it clearly. 1st of all pre-calculate the factors sum till 1000 and keep the sum in the corresponding index. for example, suppose the sum of the factors of 101 is 1+101 = 102. so keep array[101] = 102. similarly keep 1 to 1000 all the factors sum to its corresponding index. now for a number N just check for 1000 to 1 iteratively which index's sum is equal to N. print the index number and if not found just print -1.
an accepted code is as follows:
#include<bits/stdc++.h>
using namespace std;
vector<int> v;
void pre()
{
for(int i=1;i<=1000;i++)
{
int sum=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
sum=sum+j;
}
}
v.push_back(sum);
}
}
int main()
{
pre();
int n,q=1;
while(cin>>n && n)
{
int s=0,p;
for(int i=v.size();i>=0;i--)
{
if(v[i]==n)
{
s=1;
p=i+1;
break;
}
}
if(s==1)
{
printf("Case %d: %d\n",q,p);
}
else
{
printf("Case %d: %d\n",q,-1);
}
q++;
}
return 0;
}
This problem is easy to implement if you can understand it clearly. 1st of all pre-calculate the factors sum till 1000 and keep the sum in the corresponding index. for example, suppose the sum of the factors of 101 is 1+101 = 102. so keep array[101] = 102. similarly keep 1 to 1000 all the factors sum to its corresponding index. now for a number N just check for 1000 to 1 iteratively which index's sum is equal to N. print the index number and if not found just print -1.
an accepted code is as follows:
#include<bits/stdc++.h>
using namespace std;
vector<int> v;
void pre()
{
for(int i=1;i<=1000;i++)
{
int sum=0;
for(int j=1;j<=i;j++)
{
if(i%j==0)
{
sum=sum+j;
}
}
v.push_back(sum);
}
}
int main()
{
pre();
int n,q=1;
while(cin>>n && n)
{
int s=0,p;
for(int i=v.size();i>=0;i--)
{
if(v[i]==n)
{
s=1;
p=i+1;
break;
}
}
if(s==1)
{
printf("Case %d: %d\n",q,p);
}
else
{
printf("Case %d: %d\n",q,-1);
}
q++;
}
return 0;
}
No comments:
Post a Comment