problem link-click here
here's only one problem which is understanding how to determine the 9-degree of N. this is simple. this indicates recursively how many steps needed to get 9. let 99999 is the input N.
now sum= 9+9+9+9+9=45 //45 is divisible by 9
again sum= 4+5=9 here we get 9 by two steps
1st step adding string and 2nd step is again adding the sum value.. this will continue until we get 9 from a given string and the steps we need to get 9 is our desired 9-degree N.
an accepted code is given below:
#include<bits/stdc++.h>
using namespace std;
int value(string str)
{
int sum=0;
for(int i=0;i<str.length();i++)
{
sum=sum+(str[i]-48);
}
return sum;
}
int recursion(int sum)
{
int i=1;
if(sum%9==0)
{
while(sum!=9 && sum>9)
{ int r=0;
while(sum!=0)
{
r=r+(sum%10);
sum=sum/10;
}
sum=r;
i++;
}
return i;
}
else
{
return -1;
}
}
int main()
{
string str;
while(cin>>str && str!="0")
{
int sum=value(str);
int i=recursion(sum);
cout<<str;
if(i==-1)
{
printf(" is not a multiple of 9.\n");
}
else if(str=="9")
{
printf(" is a multiple of 9 and has 9-degree 1.\n");
}
else
{
printf(" is a multiple of 9 and has 9-degree %d.\n",i);
}
}
return 0;
}
here's only one problem which is understanding how to determine the 9-degree of N. this is simple. this indicates recursively how many steps needed to get 9. let 99999 is the input N.
now sum= 9+9+9+9+9=45 //45 is divisible by 9
again sum= 4+5=9 here we get 9 by two steps
1st step adding string and 2nd step is again adding the sum value.. this will continue until we get 9 from a given string and the steps we need to get 9 is our desired 9-degree N.
an accepted code is given below:
#include<bits/stdc++.h>
using namespace std;
int value(string str)
{
int sum=0;
for(int i=0;i<str.length();i++)
{
sum=sum+(str[i]-48);
}
return sum;
}
int recursion(int sum)
{
int i=1;
if(sum%9==0)
{
while(sum!=9 && sum>9)
{ int r=0;
while(sum!=0)
{
r=r+(sum%10);
sum=sum/10;
}
sum=r;
i++;
}
return i;
}
else
{
return -1;
}
}
int main()
{
string str;
while(cin>>str && str!="0")
{
int sum=value(str);
int i=recursion(sum);
cout<<str;
if(i==-1)
{
printf(" is not a multiple of 9.\n");
}
else if(str=="9")
{
printf(" is a multiple of 9 and has 9-degree 1.\n");
}
else
{
printf(" is a multiple of 9 and has 9-degree %d.\n",i);
}
}
return 0;
}
No comments:
Post a Comment