For a given n, I am trying to find the smallest number that is divisible by n, and also has sum of digits as n.
For example: For n = 10, Output should be 190, For n = 11, Output should be 209
I have adopted the Breadth First Traversal Approach to solve my problem.
#include <iostream>
#include <queue>
#include <string>
using namespace std;
class State{
public:
int sum,rem;
string str;
State(int s,int r,string st){
sum = s;
rem = r;
str = st;
}
};
int main() {
int n,newSum,newRem;
queue<State> q;
cin>>n;
bool visited[n+1][n+1] = {0};
State curr = State(0,0,"");
q.push(curr);
visited[0][0] = 1;
while(!q.empty()){
curr = q.front();
q.pop();
if(curr.sum==n && curr.rem==0){
cout<<curr.str<<endl;
break;
}
for(int j=0; j<=9; j++){
newSum = curr.sum + j;
newRem = (curr.rem*10+j)%n;
if(newSum > n){
break;
}
else if(!visited[newSum][newRem]){
curr = State(curr.sum+j, ((curr.rem*10)+j)%n,curr.str+to_string(j));
q.push(curr);
visited[newSum][newRem] = 1;
}
}
}
retu 0;
}
My code, retus a number that satisfies the condition, but it is not the smallest possible number. For n = 10, my code gives 12340 For n = 11, my code gives 1010207
Ideone link: http://ideone.com/c4W48N
