Find the box number containing the kth candy

Viewed 14

You have N boxes numbered 1 through N and K candies numbered 1 through K. You put the candies in the boxes in the following order : 1st candy in 1st box 2nd candy in 2nd box and so on till nth candy then start from n-1 box to 1 box (ie 1,2,3,...,n,n-1,n-2....,n-1,1,2,3,...) Find the box containing kth candy where did i go wrong?

int solve(int n,int k)
{
    if(k<n)
    {
        return k;
    }
    else
    {
       while(k>n)
       {
        k= k-n;
        if(k==n) return 1;
        if(k<n) return n-k+1;
       }
    }
}
0 Answers
Related