Bom dia,
eu estou a tentar resolver o seguinte problema.
Dado um t e um c, preciso de encontrar o maior número n possível tal que c * n * log(n) < t. Ou seja, preciso de encontrar o número n mais próximo de t que satisfaça essa conta.
O código que fiz é o seguinte, mas não satisfaz todas as condições que devia e não percebo porquê?
Problema tirado do TopCoder:
Problem Statement
You have implemented a sorting algorithm that requires exactly cn lg(n) nanoseconds to sort n integers. Here lg denotes the base-2 logarithm. Given time nanoseconds, return the largest double n such that cn lg(n) <= time.
Definition
Class :
SortEstimate
Method :
howMany
Parameters :
int , int
Returns :
double
Method signature :
double howMany ( int c , int time )
( be sure your method is public )
Notes
lg(n) = ln(n)/ln(2) where ln denotes the natural log.
Your return value must have a relative or absolute error less than 1e-9.
Constraints
c will be between 1 and 100 inclusive.
time will be between 1 and [telefone removido] inclusive.
Examples
0)
1
8
Returns: 4.0
Given 8 nanoseconds we can sort 4 integers since
14 lg(4) = 4*2 = 8
1)
2
16
Returns: 4.0
Now that c = 2 we need twice as many nanoseconds to sort 4 integers.
2)
37
12392342
Returns: 23104.999312341137
We can almost sort 23105 integers, but not quite.
3)
1
[telefone removido]
Returns: 7.637495090348122E7
Largest possible return.
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. ©2003, TopCoder, Inc. All rights reserved.
public class SortEstimate {
public double howMany ( int c , int time )
{
//1*4*log(4) = 4*2 = 8
double l = 0 ;
double h = Double . MAX_VALUE / 100 ;
double m ;
double dtime = time / c ;
for ( int i = 0 ; i < 1000 ; i ++ )
{
m = ( l + h ) / 2 ;
if ( m * ( Math . log ( m ) / Math . log ( 2 )) > dtime )
h = m ;
else
l = m ;
}
return ( dtime - h < dtime - l ) ? h : l ;
}
public static void main ( String [] args ) {
SortEstimate se = new SortEstimate ();
System . out . println ( se . howMany ( 37 , 12392342 ));
}
}
Sabem porquê?