0

In the below example, countOdds() takes around 23ms & countEven() takes around 1ms. Even if I create a copy of countOdds() & call second time, that takes 1ms only. I want to understand why that is happening ?

Output: Number of odd numbers is 5 Time taken is 23ms No of even numbers is 5 Time taken is 1ms

Example public class Sol {

public static void main(String[] args) {
    long startTime = System.currentTimeMillis();
    System.out.println("Number of odd numbers is " + new Sol().countOdds(9, 17));//3
    long endTime = System.currentTimeMillis();
    System.out.println("Time taken is "+ (endTime-startTime) +"ms");
    
    long startTimeAnother = System.currentTimeMillis();
    System.out.println("No of even numbers is " + new Sol().countEven(21, 30));
    long endTimeAnother = System.currentTimeMillis();
    System.out.println("Time taken is "+ (endTimeAnother-startTimeAnother) +"ms");
}
public int countOdds(int low, int high) {
    return (int) IntStream.rangeClosed(low, high).filter(n -> n%2!=0).count();
               
}

public int countEven(int low, int high) {
    return (int) IntStream.rangeClosed(low, high).filter(n -> n%2==0).count();
               
}

}

0 Answers0