和爲S的連續正數序列(JS)

題目描述
小明很喜歡數學,有一天他在做數學作業時,要求計算出9~16的和,他馬上就寫出了正確答案是100。但是他並不滿足於此,他在想究竟有多少種連續的正數序列的和爲100(至少包括兩個數)。沒多久,他就得到另一組連續正數和爲100的序列:18,19,20,21,22。現在把問題交給你,你能不能也很快的找出所有和爲S的連續正數序列? Good Luck!
輸出描述:
輸出所有和爲S的連續正數序列。序列內按照從小至大的順序,序列間按照開始數字從小到大的順序

function FindContinuousSequence(n)
{
    let res = [];
  let t = [];
  for(let i = 0;i <= n;i++){
    t.push(i);
  }
  for(let i = parseInt(n / 2) + 1;i >= 2 ; i--){
    let temp = n / i;
    // 能整除 i , 且 i 是奇數的時候 必定存在和爲n的序列
    if(i % 2 === 1 && temp === parseInt(temp)){
      let left = temp - (i - 1) / 2;
      let right = temp + (i - 1) / 2;
      if(left > 0){
        let r = t.slice(left , right + 1);
        res.push(r);
      }  
    }
    // 除以i之後得.5的結果 , 且 i 是偶數的時候 必定存在和爲n的序列
    if(i % 2 === 0 && temp !== parseInt(temp) && temp * 2 === parseInt(temp * 2)){
      let left = parseInt(temp) - (i / 2 - 1);
      let right = parseInt(temp) + i / 2;
      if(left > 0){
        let r = t.slice(left ,  right+ 1);
        res.push(r);
      }
    }
  }
  return res;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章