Number of chocolates left after k iterations
Last Updated :
18 Jun, 2022
Given a pile of chocolates and an integer ‘k’ i.e. the number of iterations, the task is to find the number of chocolates left after k iterations.
Note: In every iteration, we can choose a pile with a maximum number of chocolates, after that square root of chocolate remains and rest is eaten.
Examples:
Input: Chocolates = 100000000, Iterations = 3
Output: 10
Input: Chocolates = 200, Iterations = 2
Output: 4
Note: Output is printed after rounding off the value as in the 2nd example, the output will be around 3.76 approx.
Approach:
It is given that maximum no. of chocolates are selected so consider total pile since it will be maximum.
Next, it is given that in the each iteration only square of chocolates are left so that by considering the mathematics equation of
(((number)n)n)...n for k times = (number)nk
Since here k times the square root is performed so the (1/2)k is powered with the N.
Consider the example of 100000000 chocolates and no. of iterations is 3 then it will be as
(((100000000)1/2)1/2)1/2 = (100000000)(1/2)3 = 10
Below is the required formula to find the remaining chocolates:
round(pow(n, (1.0/pow(2, k))))
C++
#include <bits/stdc++.h>
using namespace std;
int results( int n, int k)
{
return round( pow (n, (1.0 / pow (2, k))));
}
int main()
{
int k = 3, n = 100000000;
cout << "Chocolates left after " << k
<< " iterations are " << results(n, k);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static int results( int n, int k)
{
return ( int )Math.round(Math.pow(n,
( 1.0 / Math.pow( 2.0 , k))));
}
public static void main(String args[])
{
int k = 3 , n = 100000000 ;
System.out.print( "Chocolates left after " + k +
" iterations are " + results(n, k));
}
}
|
C#
using System;
class GFG
{
static int results( int n, int k)
{
return ( int )Math.Round(Math.Pow(n,
(1.0 / Math.Pow(2.0, k))));
}
public static void Main()
{
int k = 3, n = 100000000;
Console.Write( "Chocolates left after " +
k + " iterations are " +
results(n, k));
}
}
|
Python
def results(n, k):
return round ( pow (n, ( 1.0 /
pow ( 2 , k))))
k = 3
n = 100000000
print ( "Chocolates left after" ),
print (k),
print ( "iterations are" ),
print ( int (results(n, k)))
|
PHP
<?php
function results( $n , $k )
{
return round (pow( $n , (1.0 /
pow(2, $k ))));
}
$k = 3;
$n = 100000000;
echo ( "Chocolates left after " );
echo ( $k );
echo ( " iterations are " );
echo (results( $n , $k ));
?>
|
Javascript
<script>
function results(n , k) {
return parseInt( Math.round(Math.pow(n,
(1.0 / Math.pow(2.0, k)))));
}
var k = 3, n = 100000000;
document.write( "Chocolates left after " +
k + " iterations are " + results(n, k));
</script>
|
Output:
Chocolates left after 3 iterations are 10
Time Complexity: O(log(n))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...