How to round an integer up to the nearest multiple of 'multiple' in C

1 Answer

0 votes
#include <stdio.h>

/*
    roundUp(n, multiple)
    --------------------
    Rounds the integer n *up* to the nearest multiple of `multiple`.

    Mathematically:
        result = ceil(n / multiple) * multiple

    We use integer arithmetic for efficiency:
        (n + multiple - 1) / multiple  → smallest integer ≥ n/m
*/

int roundUp(int n, int multiple) {
    if (multiple <= 0) {
        // Defensive programming: avoid undefined behavior.
        // In real-world code, you'd throw or handle this differently.
        return n;
    }

    // Efficient integer rounding up:
    return ((n + multiple - 1) / multiple) * multiple;
}

int main(void) {
    printf("roundUp(53, 20)  = %d\n", roundUp(53, 20));
    printf("roundUp(68, 30)  = %d\n", roundUp(68, 30));
    printf("roundUp(7, 100)  = %d\n", roundUp(7, 100));
    printf("roundUp(119, 100) = %d\n", roundUp(119, 100));
    printf("roundUp(781, 100) = %d\n", roundUp(781, 100));
    printf("roundUp(1026, 100) = %d\n", roundUp(1026, 100));
    printf("roundUp(11689, 1000) = %d\n", roundUp(11689, 1000));

    return 0;
}


/*
run:

roundUp(53, 20)  = 60
roundUp(68, 30)  = 90
roundUp(7, 100)  = 100
roundUp(119, 100) = 200
roundUp(781, 100) = 800
roundUp(1026, 100) = 1100
roundUp(11689, 1000) = 12000

*/

 



answered Jul 21 by avibootz
edited Jul 21 by avibootz

Related questions

...