algorithm - How to round value UP to nearest factor of a number -
this question has answer here:
- c++: rounding nearest multiple of number 25 answers
there several questions on here how round value known multiple. example there question shows how round value specified multiple (e.g. round 9 multiple of 5 yield 10). want round value nearest factor of given number. example lets says want round value closest factor of 48.
factors of 48: 1, 2, 3, 4, 6, 8, 12, 16, 24, 48
if value 9 want round 12. way know brute force:
class program { static void main(string[] args) { const int clock = 48; int value = 9; while( value < clock && (clock % value) != 0) { value++; } console.writeline(value); } }
this works fine it's not clever or efficient, @ least suspect case. there better way round number factor of base number other brute force?
private int ucln(a, b) { return (b==0)? a:ucln(b, a%b) } // first input a>b
function main:
int u = ucln(clock, value); return clock / ((clock/u) / (value/u));
Comments
Post a Comment