Round number up to the nearest multiple of 3

前端 未结 12 2083
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 08:39

Hay, how would i go about rounded a number up the nearest multiple of 3?

ie

25 would return 27
1 would return 3
0 would return 3
6 would return 6
         


        
12条回答
  •  星月不相逢
    2020-11-28 09:25

    I'm answering this in psuedocode since I program mainly in SystemVerilog and Vera (ASIC HDL). % represents a modulus function.

    round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)
    

    This works in any case.

    The modulus of the number calculates the remainder, subtracting that from the divisor results in the number required to get to the next divisor multiple, then the "magic" occurs. You would think that it's good enough to have the single modulus function, but in the case where the number is an exact multiple of the divisor, it calculates an extra multiple. ie, 24 would return 27. The additional modulus protects against this by making the addition 0.

提交回复
热议问题