Ceiling Division

easy Programming Basics

Problem

Divide a by b and round UP to the next whole number, using only integer operations. For example 7 / 2 is 3.5, so print 4. Input: a and b with a >= 0 and b > 0.

Constraints

  • 0 <= a <= 10^12
  • 1 <= b <= 10^9

Examples

Input

7 2

Output

4

Solutions

Best approachTime O(1)Space O(1)

If a is an exact multiple of b nothing changes. Otherwise the added b - 1 carries the answer over to the next whole number. One line, no branches.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Round up a division.
 * Input   : a and b.
 * Output  : Ceiling of a / b.
 * Approach: Add b - 1.
 * 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 long solve(long a, long b) {
        // Step 1: Adding (b - 1) before the division pushes any non-zero remainder up to the next whole number.
        return (a + b - 1) / b;
    }

    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 (2)
  1. What is 7 + 1 divided by 2?
  2. Why does an exact multiple stay the same?