Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the next multiple of 10 of any integer?

Tags:

c

algorithm

math

Dynamic integer will be any number from 0 to 150.

i.e. - number returns 41, need to return 50. If number is 10 need to return 10. Number is 1 need to return 10.

Was thinking I could use the ceiling function if I modify the integer as a decimal...? then use ceiling function, and put back to decimal?
Only thing is would also have to know if the number is 1, 2 or 3 digits (i.e. - 7 vs 94 vs 136)

Is there a better way to achieve this?

Thank You,

like image 742
T.T.T. Avatar asked Mar 08 '10 18:03

T.T.T.


People also ask

How do you find the next multiple of 10?

Multiples of 10 are 10, 20, 30, 40, 50, 60, etc. Therefore, 40 is the solution to Harry's puzzle.

How do you find multiples of integers?

To find multiples of a number, multiply the number by any whole number. For example, 5 × 3 = 15 and so, 15 is the third multiple of 5. For example, the first 5 multiples of 4 are 4, 8, 12, 16 and 20. 1 × 4 = 4, therefore the 1st multiple of 4 is 4.

What is a multiple of an integer?

Generally: The multiples of an integer are all the numbers that can be made by multiplying that integer by any integer. Because 21 can be written as 3 × 7, it is a multiple of 3 (and a multiple of 7). Though 21 can also be written as 2 × 10 , it is not generally considered a multiple of 2 (or 10.


2 Answers

n + (10 - n % 10) 

How this works. The % operator evaluates to the remainder of the division (so 41 % 10 evaluates to 1, while 45 % 10 evaluates to 5). Subtracting that from 10 evaluates to how much how much you need to reach the next multiple.

The only issue is that this will turn 40 into 50. If you don't want that, you would need to add a check to make sure it's not already a multiple of 10.

if (n % 10)     n = n + (10 - n % 10); 
like image 102
R Samuel Klatchko Avatar answered Sep 28 '22 10:09

R Samuel Klatchko


You can do this by performing integer division by 10 rounding up, and then multiplying the result by 10.

To divide A by B rounding up, add B - 1 to A and then divide it by B using "ordinary" integer division

Q = (A + B - 1) / B  

So, for your specific problem the while thing together will look as follows

A = (A + 9) / 10 * 10 

This will "snap" A to the next greater multiple of 10.

The need for the division and for the alignment comes up so often that normally in my programs I'd have macros for dividing [unsigned] integers with rounding up

#define UDIV_UP(a, b) (((a) + (b) - 1) / (b)) 

and for aligning an integer to the next boundary

#define ALIGN_UP(a, b) (UDIV_UP(a, b) * (b)) 

which would make the above look as

A = ALIGN_UP(A, 10); 

P.S. I don't know whether you need this extended to negative numbers. If you do, care should be taken to do it properly, depending on what you need as the result.

like image 33
AnT Avatar answered Sep 28 '22 12:09

AnT