计算一个数组的最小公倍数。
有意思
比来很火的 github 上的库 30-seconds-of-code ,特别有意思,代码也很优雅。
arrayGcd
Calculates the greatest common denominator (gcd) of an array of numbers.
Use Array.reduce() and the gcd formula (uses recursion) to calculate the greatest common denominator of an array of numbers.
- const arrayGcd = arr =>{
- const gcd = (x, y) => !y ? x : gcd(y, x % y);
- return arr.reduce((a,b) => gcd(a,b));
- }
- // arrayGcd([1,2,3,4,5]) -> 1
- // arrayGcd([4,8,12]) -> 4
计算数组的最大年夜公约数。
应用 Array.reduce() 和 gcd 公式(应用递归)来计算一个数组的最大年夜公约数。
gcd 即欧几里德算法,具体不表,自查。这里用到了数组的reduce办法,相当简洁,reduce不太懂得的话,看下 mdn 就明白。
arrayLcm
Calculates the lowest common multiple (lcm) of an array of numbers.
Use Array.reduce() and the lcm formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
- const arrayLcm = arr =>{
- const gcd = (x, y) => !y ? x : gcd(y, x % y);
- const lcm = (x, y) => (x*y)/gcd(x, y)
- return arr.reduce((a,b) => lcm(a,b));
- }
- // arrayLcm([1,2,3,4,5]) -> 60
- // arrayLcm([4,8,12]) -> 24
- ➜ code python
- Python 3.6.4 (default, Dec 23 2017, 10:37:40)
- [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
- Type "help", "copyright", "credits" or "license" for more information.
- >>> import math
- >>> arr = [1,2,3,4,5]
- >>> size = 2
- >>> for i in range(math.ceil(len(arr) / size)):
- ... print('index: ', i)
- ...
- index: 0
- index: 1
- index: 2
应用 Array.reduce() 和 lcm 公式(应用递归)来计算一个数组的最大年夜公约数。
- ➜ code cat arrayGcd.js
- const arrayGcd = arr => {
- const gcd = (x, y) => !y ? x : gcd(y, x % y);
- return arr.reduce((a, b) => gcd(a, b));
- }
- console.log(arrayGcd([1, 2, 3, 4, 5]));
推荐阅读
NodeJs爬虫抓取古代典籍,共计16000个页面心得体会总结及项目分享
【限时免费】岁尾最强一次云计算大年夜会,看传统、社区、互联网企业若何碰撞? 之前研究数据,零零碎散的写过一些数据抓取的爬虫,不过写的比较随便。有很多处所如今看起来并不是很合理 这>>>详细阅读
地址:http://www.17bianji.com/lsqh/40136.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示