algorithm - How to round value UP to nearest factor of a number -


this question has answer here:

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

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -