A problem with stairs
by hemangsarkar, Sep 11, 2015, 6:44 PM
This is a problem from Codeforces.
Q)
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input:
The single line contains two space separated integers n, m (0 < n ≤ 10000, 1 < m ≤ 10).
Output:
Print a single integer — the minimal number of moves being a multiple of m. If there is no way he can climb satisfying condition print - 1 instead.
Solution
Q)
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.
What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?
Input:
The single line contains two space separated integers n, m (0 < n ≤ 10000, 1 < m ≤ 10).
Output:
Print a single integer — the minimal number of moves being a multiple of m. If there is no way he can climb satisfying condition print - 1 instead.
Solution
#include<iostream>
using namespace std;
int main()
{
int n,m,ans;
cin>>n>>m;
if(n<m)
cout<<"-1";
else if(n==m)
cout<<n;
else{
if(n%2==0)
ans = n/2; /*since we want minimum number of jumps, we start with the maximum number of 2 jumps we can have*/
else ans = 1 + (n-1)/2;
if(ans%m==0)
cout<<ans;
else{
while(ans%m!=0)
ans+=1; /*split a 2 jump into two 1 jumps. this adds one to the answer since the number of jumps increases by 1. we keep increasing until a multiple is met.*/
cout<<ans;
}
}
return 0;
}
using namespace std;
int main()
{
int n,m,ans;
cin>>n>>m;
if(n<m)
cout<<"-1";
else if(n==m)
cout<<n;
else{
if(n%2==0)
ans = n/2; /*since we want minimum number of jumps, we start with the maximum number of 2 jumps we can have*/
else ans = 1 + (n-1)/2;
if(ans%m==0)
cout<<ans;
else{
while(ans%m!=0)
ans+=1; /*split a 2 jump into two 1 jumps. this adds one to the answer since the number of jumps increases by 1. we keep increasing until a multiple is met.*/
cout<<ans;
}
}
return 0;
}
This post has been edited 1 time. Last edited by hemangsarkar, Sep 11, 2015, 6:45 PM