1

There are several questions on here how to round a value to a known multiple. For example there is this question but that shows how to round a value to a specified multiple (e.g. round 9 to multiple of 5 will yield 10). I want to round a value up to the nearest factor of a given number. For example lets says I want to round up a value to the closest factor of 48.

Factors of 48: 1, 2, 3, 4, 6, 8, 12, 16, 24, 48

If my value is 9 I would want to round up to 12. The only way I know to do this is with 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 but it's not clever or efficient, at least I suspect that to be the case. Is there a better way to round a number up to a factor of a base number other than brute force?

Community
  • 1
  • 1
scubasteve
  • 2,718
  • 4
  • 38
  • 49
  • Clarified the problem statement and addressed why the supplied reference duplicate question isn't applicable. – scubasteve Oct 15 '15 at 04:11
  • Lame that this was closed as a dupe but the referenced duplicate question and solution do NOT address my issue. David, did you read my actual question or base your decision on the title alone? – scubasteve Oct 19 '15 at 03:19
  • Came here looking for the same. Disappointing to find this incorrectly closed. – lambgrp425 Nov 05 '15 at 19:15

1 Answers1

0
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));
Nguyễn Hải Triều
  • 1,454
  • 1
  • 8
  • 14