Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • This might be a possible use case for the factor command:- factor 8192 outputs '8192: 2 2 2 2 2 2 2 2 2 2 2 2 2' Commented Jun 17 at 1:13
  • 2
    @JeremyBoden, factor feels a bit awkward here, it gives both too much information (the whole breakdown to prime factors, while just divisibility by 4096 is needed), and too little information (it doesn't help in rounding up) Commented Jun 17 at 8:41
  • You could also use if (remainder != 0) num = num + divisor - remainder; printf "%i ", num, since the other branch is a no-op Commented Jun 17 at 9:40
  • 2
    ((x-1)|4095)+1 uses bitwise OR to safely round up without overflow, and without an expensive division operation or checking remainders. This of course only works for power-of-2 divisors because it relies on binary integer representations. Does /bin/sh support $(( )) math at all? I think that's not part of POSIX sh, so your script should be using /bin/bash or /bin/ksh or anything other than /bin/sh. Bash supports bitwise-OR with |. If you want to check whether rounding-up happened, check for equality of input vs. output. Commented Jun 17 at 10:25
  • 3
    @PeterCordes, $(( )) is standard and the standard refers to C operators in the context of arithmetic expansion, so ((x-1)|4095)+1 should be fine. (It explicitly doesn't require ++ and --, and the "standalone" (( .. )) construct isn't standard.) Commented Jun 18 at 11:16