I am currently working on a problem of an online judge (not a contest). The program must calculate how many years will require for the population A (which is always less than B) to be higher than B. If the time is more than a Century then print "More than a century" in Portuguese.
Input
1
90000 120000 5.5 3.5
Where 1 is the number of test cases and in the next line are the population of A, population of B, percentage growing rate of A and percentage growing rate of B. For this input the result will be 16 years.
However, my code keeps exceeding the time limit, which is only 1 second. I have used Scanner
and System.out.print()
however I have been told that such methods will make my code slower and will consume more memory, that is way I buffered the input and output. I cannot use types such as long
or int
as the data stored the variables is longer than those values.
import java.io.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws NumberFormatException, IOException{
java.io.InputStreamReader iSR = new java.io.InputStreamReader(System.in);
java.io.BufferedReader bR = new java.io.BufferedReader(iSR, 16 * 1024);
BufferedWriter bW = new BufferedWriter(new OutputStreamWriter(System.out));
String tL;
BigDecimal PRA = BigDecimal.ZERO, PRB = BigDecimal.ZERO, PA = BigDecimal.ZERO, PB = BigDecimal.ZERO;
int input = Integer.parseInt(bR.readLine());
for(int j = 0; j < input; j++){
tL = bR.readLine();
String [] = arr = tL.split(" ");
PA = BigDecimal.valueOf(Integer.parseInt(arr[0]));
PB = BigDecimal.valueOf(Integer.parseInt(arr[1]));
PRA = BigDecimal.valueOf(Double.parseDouble(arr[2]));
PRB = BigDecimal.valueOf(Double.parseDouble(arr[3]));
PRA = PRA.divide(BigDecimal.valueOf(100)); PRA = PRA.add(BigDecimal.ONE);
PRB = PRB.divide(BigDecimal.valueOf(100)); PRB = PRB.add(BigDecimal.ONE);
int i = 1;
while(PA.compareTo(PB) < 0 && i < 103){
BigDecimal ibd = BigDecimal.valueOf(i);
PA = PA.multiply(PRA).multiply(ibd);
PB = PB.multiply(PRB).multiply(ibd);
i++;
}
i--;
if(i > 100) bW.write("Mais de 1 seculo.\n");
else bW.write(String.valueOf(i) + " anos.\n");
bW.flush();
}
}
}