# 算法设计：如何解决2个鸡蛋和K层鸡蛋掉落难题？

2021年3月19日17:07:31 发表评论 800 次浏览

## 本文概述

Input : k = 10
Output : 4
We first try from 4-th floor. Two cases arise, (1) If egg breaks, we have one egg left so we
need three more trials.
(2) If egg does not break, we try next from 7-th
floor. Again two cases arise.
We can notice that if we choose 4th floor as first
floor, 7-th as next floor and 9 as next of next floor, we never exceed more than 4 trials.

Input : k = 100
Output : 14

## 推荐：请尝试以下方法{IDE}首先, 在继续解决方案之前。

x * (x + 1)/2 >= k
The optimal value of x can be written as, ⌈((-1 + √(1+8k))/2)⌉

## C ++

// CPP program to find optimal number of trials
// for k floors and 2 eggs.
#include<bits/stdc++.h>
using namespace std;

int twoEggDrop( int k)
{
return ceil ((-1.0 + sqrt (1 + 8*k))/2.0);
}

int main()
{
int k = 100;
cout << twoEggDrop(k);
return 0;
}

## Java

// Java program to find
// optimal number of trials
// for k floors and 2 eggs.
import java.io.*;

class GFG
{
static int twoEggDrop( int k)
{
return ( int )Math.ceil((- 1.0 +
Math.sqrt( 1 + 8 * k)) / 2.0 );
}

// Driver code
public static void main (String[] args)
{
int k = 100 ;
System.out.println(twoEggDrop(k));
}
}

// This code is contributed

## Python3

# Python3 program to find optimal number
# of trials for k floors and 2 eggs.
import math as mt

def twoEggDrop(k):
return mt.ceil(( - 1.0 +
mt.sqrt( 1 + 8 * k)) / 2 )

# Driver Code
k = 100
print (twoEggDrop(k))

# This code is contributed
# by Mohit Kumar

## C#

// C# program to find optimal number
// of trials for k floors and 2 eggs.
class GFG
{
static int twoEggDrop( int k)
{
return ( int )System.Math.Ceiling((-1.0 +
System.Math.Sqrt(1 + 8 * k)) / 2.0);
}

// Driver code
public static void Main ()
{
int k = 100;
System.Console.WriteLine(twoEggDrop(k));
}
}

// This code is contributed
// by mits

## 的PHP

<?php
// PHP program to find optimal number
// of trials for k floors and 2 eggs.

function twoEggDrop( \$k )
{
return ceil ((-1.0 +
sqrt(1 + 8 * \$k )) / 2.0);
}

// Driver Code
\$k = 100;
echo twoEggDrop( \$k );

// This code is contributed
// by Akanksha Rai

14

O(1)