Looking for alternative algorithms
Below are the ones l have made but are being flagged as incorrect by the Online Judge on a coding website.
After declaring variable of int data type k, l received an input from the console using cin(). Since the constraints of the question read that the possible number(s) is/are between 1 and 20000, l first off opened a for loop using these conditions. At every iteration of i (one after the other), the number is tested whether its digits sum up to 10 and if they do, whether its the kth number whose digits are of sum 10.
To find the sum of digits, l used either a recursive function or an iterative method using a while loop. Hence the two snippets of codes. In both methods, the sum is calculated by finding the digits first using modular % operator and division operator /. The sum is figured out and then further tested if its equal to 10 and if Yes, it is also tested if its the K th element by means of keeping count of all previous similar elements. After all conditions are satisfied, only then is the value i outputted using cout().
#include <bits/stdc++.h>
using namespace std;
//recursion to get sum of digits.
*int sum(int d)
{
return d==0?0:d%10+sum(d/10);
}*
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
int t;
cin>>t;
while(t-- >0)
{
int k;
cin>>k;
for(int i=0;i<20000;i++)
{
int total=sum(i);
if(total==10)
{
--k;
if(k==0)
cout<<i<<"\n";
}
}
}
return 0;
}
Second one, l used iterations(while loop) to deduce sum of digits
#include <bits/stdc++.h>
using namespace std;
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(NULL);
int t;
cin>>t;
while(t-- >0)
{
int k;
cin>>k;
for(int i=0;i<20000;i++)
{
int sum=0,d=i;
*while(d!=0)
{
sum+=d%10;
d/=10;
}*
if(sum==10)
{
--k;
if(k==0)
cout<<i<<"\n";
}
}
}
return 0;
}
So l need alternative algorithms of better efficiency. Thanks in advance