📜  蛋糕分配问题

📅  最后修改于: 2021-04-25 00:35:45             🧑  作者: Mango

给定两个整数NM ,其中N是按顺时针方向围成一个圆圈的朋友数,M是蛋糕数。任务是分配的蛋糕第i个朋友后,计算蛋糕的左边的数字。如果蛋糕数量少于要求的数量,蛋糕的分配将停止。

例子:

方法:

  • 检查从m个蛋糕中可以分配多少个蛋糕周期。
  • 计算1个周期的蛋糕数,即
    sum = n * (n + 1) / 2
  • 现在按总和潜水M,我们得到周期数+一些余数。
  • 现在,检查剩余的蛋糕数量又可以分发给x个朋友。
  • x的值可以通过求解二次方程式轻松实现
    remainder = x * (x + 1) / 2

下面是上述方法的实现:

C++
// C++ implementation of the approach 
#include
using namespace std;
  
// Function to return the 
// remaining count of cakes 
int cntCakes(int n, int m)
{ 
  
    // Sum for 1 cycle 
    int sum = (n * (n + 1)) / 2;
  
    // no. of full cycle and remainder 
    int quo = m/sum ;
    int rem = m % sum ;
    double ans = m - quo * sum ;
  
    double x = (-1 + pow((8 * rem) + 1, 0.5)) / 2;
      
    ans = ans - x * (x + 1) / 2;
  
    return int(ans);
}
  
// Driver Code
int main () 
{
    int n = 3;
    int m = 8; 
    int ans = cntCakes(n, m);
    cout << (ans);
}
  
// This code is contributed by Surendra_Gangwar


Java
// Java implementation of the approach 
class GFG 
{
      
    // Function to return the 
    // remaining count of cakes 
    static int cntCakes(int n, int m)
    { 
      
        // Sum for 1 cycle 
        int sum = (n * (n + 1)) / 2;
      
        // no. of full cycle and remainder 
        int quo = m/sum ;
        int rem = m % sum ;
        double ans = m - quo * sum ;
      
        double x = (-1 + Math.pow((8 * rem) + 1, 0.5)) / 2;
          
        ans = ans - x * (x + 1) / 2;
      
        return (int)ans;
    }
  
    // Driver Code
    public static void main (String[] args) 
    {
        int n = 3;
        int m = 8; 
        int ans = cntCakes(n, m);
        System.out.println(ans);
    }
}
  
// This code is contributed by AnkitRai01


Python3
# Python3 implementation of the approach
  
# Function to return the 
# remaining count of cakes
def cntCakes(n, m):
  
    # Sum for 1 cycle
    sum = (n*(n + 1))//2
  
    # no. of full cycle and remainder
    quo, rem = m//sum, m % sum
    ans = m - quo * sum
  
    x = int((-1 + (8 * rem + 1)**0.5)/2)
    ans = ans - x*(x + 1)//2
  
    return ans
  
# Driver code
def main():
  n = 4
  m = 11
  ans = cntCakes(n, m)
  print(ans)
  
main()


C#
// C# implementation of the approach
using System;
  
class GFG
{
    // Function to return the 
    // remaining count of cakes 
    static int cntCakes(int n, int m)
    { 
      
        // Sum for 1 cycle 
        int sum = (n * (n + 1)) / 2;
      
        // no. of full cycle and remainder 
        int quo = m/sum ;
        int rem = m % sum ;
        double ans = m - quo * sum ;
      
        double x = (-1 + Math.Pow((8 * rem) + 1, 0.5)) / 2;
          
        ans = ans - x * (x + 1) / 2;
      
        return (int)ans;
    }
  
    // Driver Code
    static public void Main ()
    {
        int n = 3;
        int m = 8; 
        int ans = cntCakes(n, m);
        Console.Write(ans);
    }
}
  
// This code is contributed by ajit.


输出:
0

时间复杂度: O(1)