Search code examples
mathalgebra

How to find the range for a given number, interval and start value?


Provided the below values

  1. start value = 1
  2. End Value = 20
  3. Interval = 5

I have been provided a number 6. I have to find the range of numbers in which the number 6 falls say now the answer is 6-10.

If the given number is greater than the end value then return the same number.

Is there any formula so that i can generate the range for the number?

UPDATE

I tried the below solution, But it is not working if the range interval is changed,

 $end_value = $start_value + $range_interval;

// we blindly return the last term if value is greater than max value
if ($input_num > $end_value) {
  return '>' . $end_value;
}

// we also find if its a first value
if ($input_num <= $end_value && $value >= $start_value) {
  return $start_value . '-' . $end_value;
}

// logic to find the range for a given integer
$dived_value = $input_num/$end_value;

// round the value to get the exact match
$rounded_value = ceil($dived_value);

$upper_bound_range = $rounded_value*$end_value;

$lower_bound_range = $upper_bound_range - $end_value;

return $lower_bound_range . '-'. $upper_bound_range;

Solution

  • In (c-style) pseudocode:

    // Integer division assumed
    rangeNumber = (yourNumber - startValue) / rangeLength;
    lower_bound_range = startValue + rangeNumber*rangeLength;
    upper_bound_range = lower_bound_range + rangeLength-1;
    

    For your input:

    rangeNumber = (6-1)/5 = 1
    lower_bound_range = 1 + 5*1 = 6
    upper_bound_range = 10
    

    and so range is [6, 10]