So, the problem task is:
Given an integer , compute the minimum number of operations needed to obtain the number starting from the number 1.
And here is my code for doing this:
#include<bits/stdc++.h>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n+1);
for(int i = 0; i < n+1; i++)
{
v[i] = 0;
}
v[1] = 1;
for(int i = 1; i <= v.size() - 1; i++)
{
if((v[i + 1] == 0) || (v[i + 1] > v[i] + 1))
{
v[i + 1] = v[i] + 1;
}
if((2*i <= n) && (v[2*i] == 0 || v[2*i] > v[i] + 1))
{
v[2*i] = v[i] + 1;
}
if((3*i <= n) && (v[3*i] == 0 || v[3*i] > v[i] + 1))
{
v[3*i] = v[i] + 1;
}
}
vector<int> solution;
while(n > 1)
{
solution.push_back(n);
if(v[n - 1] == v[n] - 1)
{
n = n-1;
}
else if(n%2 == 0 && v[n/2] == v[n] - 1)
{
n = n/2;
}
else if(n%3 == 0 && v[n/3] == v[n] - 1)
{
n = n/3;
}
}
solution.push_back(1);
reverse(solution.begin(), solution.end());
for(size_t k = 0; k < solution.size(); k++)
{
cout << solution[k] << ' ';
}
}
I am not able to figure out any mistake. This is not giving me any output. It will be great if you could help me out. Input and output have been shown here:
Input:
5
Output:
3
1 2 4 5
So, basically you have to give number of operations needed to do this task for n and provide the sequence of intermediate numbers.