如何找到给定数字,间隔和起始值的范围?

时间:2013-01-29 09:45:50

标签: math algebra

提供以下值

  1. 起始值= 1
  2. 结束值= 20
  3. Interval = 5
  4. 我已经提供了一个数字6.我必须找到6号下降的数字范围,现在答案是6-10。

    如果给定的数字大于结束值,则返回相同的数字。

    是否有任何公式可以生成数字的范围?

    更新

    我尝试了以下解决方案,但是如果更改了范围间隔,则无法正常工作

     $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;
    

2 个答案:

答案 0 :(得分:1)

(c风格)伪代码:

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

您的意见:

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

所以范围是[6,10]

答案 1 :(得分:1)

答案取决于你是否谈论整数或浮点数。由于您的所有示例数字都是整数,我假设您谈论这些。我进一步假设您的所有区间包含相同数量的整数,在您的示例5中,即1 ... 5,6 ... 10,11 ... 15和16 ... 20。注意,第一个间隔中不包含0(否则第一个间隔有6个数字) 在这种情况下,答案很简单 让我们:
s第一个间隔中未包含的起始值,
区间大小,即它包含的整数,
p应提供的间隔号码,
b此区间中的第1个整数,和
e此间隔中的最后一个整数 然后:
    b = s +(p-s-1)\ i * i + 1(这里,“\”表示整数除法,即没有余数)
    e = b + i - 1
在你的例子中:
    s = 0,i = 5,p = 6,因此
    b = 0 +(6-0-1)\ 5 * 5 + 1 = 6
    e = 6 + 5 - 1 = 10