BMI Category

easy Programming Basics

Problem

Read the weight in kilograms and the height in centimetres (both whole numbers). BMI is weight / (height in metres)^2. Print underweight when BMI is below 18.5, normal when it is below 25, overweight when it is below 30, and obese otherwise. Use only whole-number maths, so that there are no rounding errors: compare weight * 10000 with the limit * height * height.

Constraints

  • 1 <= weight <= 500
  • 50 <= height <= 250

Examples

Input

70 175

Output

normal

Solutions

Best approachTime O(1)Space O(1)

Floating-point maths can give 24.999999 for a value that should be exactly 25. Comparing whole numbers (after multiplying both sides) avoids that problem. This BMI scale is a simple screening tool, not a medical diagnosis.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Find the category.
 * Input   : Weight and height.
 * Output  : A category word.
 * Approach: Whole-number comparison.
 * Time    : O(1)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String solve(long a, long b) {
        // Step 1: BMI = weight * 10000 / (height * height). To avoid decimals we compare the top part with limit * height^2.
        long squared = b * b;
        // Step 2: BMI below 18.5 means weight * 10000 < 18.5 * squared. Multiply both sides by 2 to remove the .5.
        if (a * 20000 < 37 * squared) {
            return "underweight";
        }
        if (a * 10000 < 25 * squared) {
            return "normal";
        }
        return a * 10000 < 30 * squared ? "overweight" : "obese";
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. Why do we multiply both sides by 2 for the 18.5 limit?