Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next Nearest Number Divisible By X [closed]

Tags:

c#

What I want to do essentially, is take any number a user has input, and round it to the next closest whole number divisible by X, excluding 1.

IE (X = 300):

Input = 1 Output = 300

Input = 500 Output = 600

Input = 841 Output = 900

Input = 305 Output = 300

like image 337
Laveer Avatar asked Mar 28 '13 00:03

Laveer


People also ask

How do I find the closest divisible number?

We have to find the number closest to n and divide by m. If there are more than one such number, then show the number which has maximum absolute value. If n is completely divisible by m, then return n. So if n = 13, m = 4, then output is 12.

How to tell if number is divisible by 3?

A number is divisible by 3 if sum of its digits is divisible by 3. Illustration: For example n = 1332 Sum of digits = 1 + 3 + 3 + 2 = 9 Since sum is divisible by 3, answer is Yes.

How do you make a number divisible by 5?

What is the Divisibility Rule of 5? The divisibility rule of 5 states that if the digit on the units place, that is, the last digit of a given number is 5 or 0, then such a number is divisible by 5. For example, in 39865, the last digit is 5, hence, the number is completely divisible by 5.


2 Answers

Just (integer) divide by X, add one, then multiply by X.

int output = ((input / x) + 1) * x;
like image 139
Blorgbeard Avatar answered Oct 17 '22 10:10

Blorgbeard


Based on your example behaviour I would do something like this:

double GetNearestWholeMultiple(double input, double X)
    {
      var output = Math.Round(input/X);
      if (output == 0 && input > 0) output += 1;
      output *= X;

      return output;
    }
like image 5
Francis R. Griffiths-Keam Avatar answered Oct 17 '22 09:10

Francis R. Griffiths-Keam