codewars练习(javascript)"/>
codewars练习(javascript)
文章目录
- codewars-js练习
- 2021/2/3
- github 地址
- 【1】<7kyu>【Gauß needs help! (Sums of a lot of numbers).】
- 【2】<7kyu>【Sum of odd numbers】
codewars-js练习
2021/2/3
github 地址
my github地址,上面有做的习题记录,不断更新…
【1】<7kyu>【Gauß needs help! (Sums of a lot of numbers).】
求和
example:
f(n=100) // returns 5050
f('n')//false
f(3.14)// false, "n must be an integer"
f(-10)//false, "a positive value of n is required
f(0)// false, "a value of n greater than 0 is required"
solution
<script type="text/javascript">function f(n){console.log(n);if(typeof n == 'number' && n % 1 ==0 && n > 0){var sum =0;for(var i=0;i<=n;i++){sum +=i;}return sum;}return false; }// 验证console.log(f(100));//5050console.log(f('n'));//fasleconsole.log(f(3.14));//false</script>
【2】<7kyu>【Sum of odd numbers】
Given the triangle of consecutive odd numbers:
13 57 9 1113 15 17 19
21 23 25 27 29
...
Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
example:
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
rowSumOddNumbers(42);//74088
思路
n | 第一个数 | 该行总数 | 最后一个数 |
---|---|---|---|
1 | 1 | 1 | 1 |
2 | 3 | 2 | 5 |
3 | 7 | 3 | 11 |
4 | 13 | 4 | 19 |
5 | 21 | 5 | 29 |
… | n(n-1)+1 (n>=2) | … | n(n-1)+1+(n-1)2=(n-1)(n+2)+1 |
根据n确定第一个数和该行最后一个数,从而计算。
solution
<script type="text/javascript">function rowSumOddNumbers(n) {// console.log(n);var one = n * (n-1) + 1;var last = (n-1) * (n+2) + 1;// console.log(one)var sum = 0;for(var i=one;i<=last;i=i+2){sum +=i;}return sum;}// 验证console.log(rowSumOddNumbers(1)); // 1console.log(rowSumOddNumbers(2)); // 3 + 5 = 8console.log(rowSumOddNumbers(42));//74088</script>
以上为自己思路供大家参考,可能有更优的思路。
更多推荐
codewars练习(javascript)
发布评论