【学习】算2/1,3/2,5/3,8/5,13/8,21/8........前n项之和 的两种方法

第一种 一边循环数据源一边计算乘积

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<button onclick="commit()">确定</button>
</body>
<script>
  function commit() {
    var fenzi = 2
    var fenmu = 1
    var n = 3

    //  2/1  3/2  5/3
    var newsumzi = 2
    var newsumfenmu = 1
    for (var i = 1; i < 5; i++) {
      var nextzi = fenzi + fenmu
      var nextmu = fenzi
      var tempzi = 1
      var tempmu = 1

      tempzi = newsumzi * nextmu + newsumfenmu * nextzi
      newsumzi = tempzi

      tempmu = newsumfenmu * nextmu
      newsumfenmu = tempmu

      fenzi = nextzi
      fenmu = nextmu
    }
    console.log(tempmu)
    console.log(tempzi)

    var yinshu = 1
    yinshu = gongyueshu(tempzi,tempmu); // 求最大因数
      console.log('最大公因数' + yinshu)
    if (yinshu !== 1) {
      console.log(tempzi/yinshu + '/' + tempmu/yinshu)
    }else{
      console.log(tempzi + '/' + tempmu)
    }


  }
  function gongyueshu(num1, num2) {
    var a = num1
    var b = num2

    var c = a * b
    if (a < b) {
      var temp = a
      a = b
      b = temp
    }
    while (b !== 0) {
      var temp = a % b
      a = b
      b = temp
    }
    return a
  }

</script>
</html>

 第二种,先循环数据源,然后求出分母之积

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<button οnclick="commit()">确定</button>
</body>
<script>
  function commit() {
    var x = 1
    var data = [{a: 2, b: 1}]
    for (var i = 1; i < 3; i++) {
      var temp = data[i - 1]

      data.push({a:temp.a + temp.b, b: temp.a})
      x *= b
    }
    console.log(data)
    console.log(x)
    var sum = 0
    for (var item of data) {
      sum += item.a * x / item.b
    }
    console.log(sum)

</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值