剑指offer(41)和为S的连续正数序列

题目描述

小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!

输出描述:

输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

 

题目分析

假设序列的开始数字为a,结束数字为a+i,那么有(a+i-a+1)*(a+a+i)/2=sum

也就是(i+1)*(2*a+i)=2*sum

那么我们只需要找出这样的a和i就行了,最后再根据a和i得出序列。

 

代码

function FindContinuousSequence(sum) {
  let a = 0,
    half = sum >> 1;
  const res = [];
  while (half--) {
    a++;
    let i = 1;
    while ((i + 1) * (2 * a + i) < 2 * sum) {
      i++;
    }
    if ((i + 1) * (2 * a + i) === 2 * sum) {
      const tmp = [];
      tmp.push(a);
      tmp.push(i);
      res.push(tmp);
    }
  }
  for (let i = 0; i < res.length; i++) {
    let num = res[i][1],
      k = 1;
    const tmp = [];
    tmp.push(res[i][0]);
    while (num--) {
      tmp.push(res[i][0] + k);
      k++;
    }
    res[i] = tmp;
  }
  return res;
}

 

posted @ 2018-04-10 06:50  汕大小吴  阅读(886)  评论(0编辑  收藏  举报