Peonsson
Peonsson

Reputation: 49

Simple algorithm. Can't get it right

Problem

Yraglac recently decided to try out Soylent, a meal replacement drink designed to meet all nutritional requirements for an average adult. Soylent not only tastes great but is also low-cost, which is important for Yraglac as he is currently on a budget. Each bottle provides 400 calories, so it is recommended that an individual should consume 5 bottles a day for 2000 total calories. However, Yraglac is wondering how many bottles he should consume if his daily calorie requirement is not the same as an average adult. He can only consume an integer number of bottles, and needs to consume at least his daily calorie requirement.

Src: https://open.kattis.com/problems/soylent

Input

The first line contains a single integer T ≤ 1000 giving the number of test cases. Each test case consists of a single line with an integer N (0 ≤ N ≤ 100000), the number of calories Yraglac needs in a day.

Output

For each test case, output a single line containing the number of bottles Yraglac needs to consume for the day.

Sample Input

2 2000 1600

Sample Output

5 4

My attempt

public Soylent() {

    Scanner scan = new Scanner(System.in);
    int iterations = scan.nextInt();

    for (int i = 0; i < iterations; i++) {
        int calories = scan.nextInt();
        System.out.println((int) (Math.ceil(calories / 400)));
    }
}

What am I doing wrong?

Upvotes: 0

Views: 218

Answers (2)

nbokmans
nbokmans

Reputation: 5757

It's going wrong because you are using ints in your Math.ceil call.

For example, if you run this code:

public class Main {

    public static void main(String[] args) {
        System.out.println(Math.ceil(2500/400));
        System.out.println(Math.ceil(2500/400.0));
    }
}

You will get this output:

6.0
7.0

In the second Math.ceil call you actually work with doubles, so the decimals of 2500/400 is not lost.

To make it more clear:

int result1 = 2500 / 400; //6.0
int ceiling1 = Math.ceil(result1); //6

double result2 = 2500 / 400; //6.0
int ceiling2 = Math.ceil(result2); //6

double result3 = 2500 / 400.0; //6,25
int ceiling3 = Math.ceil(result3); //7

double result4 = (double) 2500 / 400; //6.25
int ceiling4 = Math.ceil(result4); //7

So to fix your code, either make calories a double, divide by 400.0 or cast the result of calories / 400 to double.

Upvotes: 2

Peonsson
Peonsson

Reputation: 49

As Michael_T. said, calories was a double and not an integer. Thanks!

public class Soylent {

public Soylent() {

    Scanner scan = new Scanner(System.in);
    int iterations = scan.nextInt();

    for (int i = 0; i < iterations; i++) {
        double calories = scan.nextDouble();
        System.out.println((int) (Math.ceil(calories / 400)));
    }
}

Upvotes: 0

Related Questions