给定一堆巧克力和一个整数“k”,即迭代次数,任务是找到 k 次迭代后剩下的巧克力数量。
注意:在每次迭代中,我们可以选择具有最大巧克力数量的一堆巧克力,然后剩下巧克力的平方根并吃掉剩下的巧克力。
例子:
Input: Chocolates = 100000000, Iterations = 3
Output: 10
Input: Chocolates = 200, Iterations = 2
Output: 4
注意:输出在四舍五入后打印,如第二个示例,输出将约为3.76 左右。
方法:
给出了最大数量。选择巧克力,因此请考虑总堆,因为它将是最大的。
接下来,假设在每次迭代中只剩下巧克力的正方形,以便通过考虑数学方程
(((number)n)n)...n for k times = (number)nk
因为这里执行了 k 次平方根,所以 (1/2) k是用 N 供电的。
考虑 100000000 块巧克力和没有的例子。迭代次数为 3 那么它将是
(((100000000)1/2)1/2)1/2 = (100000000)(1/2)3 = 10
以下是找到剩余巧克力所需的公式:
round(pow(n, (1.0/pow(2, k))))
C++
// C++ program to find remaining
// chocolates after k iterations
#include
using namespace std;
// Function to find the chocolates left
int results(int n, int k)
{
return round(pow(n, (1.0 / pow(2, k))));
}
// Driver code
int main()
{
int k = 3, n = 100000000;
cout << "Chocolates left after " << k
<< " iterations are " << results(n, k);
return 0;
}
Java
// Java program to find remaining
// chocolates after k iterations
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
// Function to find the
// chocolates left
static int results(int n, int k)
{
return (int)Math.round(Math.pow(n,
(1.0 / Math.pow(2.0, k))));
}
// Driver code
public static void main(String args[])
{
int k = 3, n = 100000000;
System.out.print("Chocolates left after " + k +
" iterations are " + results(n, k));
}
}
// This code is contributed by Subhadeep
C#
// C# program to find remaining
// chocolates after k iterations
using System;
class GFG
{
// Function to find the
// chocolates left
static int results(int n, int k)
{
return (int)Math.Round(Math.Pow(n,
(1.0 / Math.Pow(2.0, k))));
}
// Driver code
public static void Main()
{
int k = 3, n = 100000000;
Console.Write("Chocolates left after " +
k + " iterations are " +
results(n, k));
}
}
// This code is contributed
// by ChitraNayal
Python
# Python program to find
# remaining chocolates
# after k iterations
# Function to find the
# chocolates left
def results(n, k):
return round(pow(n, (1.0 /
pow(2, k))))
# Driver code
k = 3
n = 100000000
print("Chocolates left after"),
print(k),
print("iterations are"),
print(int(results(n, k)))
# This code is contributed
# by Shivi_Aggarwal
PHP
Javascript
输出:
Chocolates left after 3 iterations are 10