作家
登录

JavaScript30秒, 从入门到放弃

作者: 来源: 2017-12-25 14:05:13 阅读 我要评论

计算一个数组的最小公倍数。


有意思

比来很火的 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.

  1. const arrayGcd = arr =>{ 
  2.   const gcd = (x, y) => !y ? x : gcd(y, x % y); 
  3.   return arr.reduce((a,b) => gcd(a,b)); 
  4. // arrayGcd([1,2,3,4,5]) -> 1 
  5. // 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.

  1. const arrayLcm = arr =>{ 
  2.  const gcd = (x, y) => !y ? x : gcd(y, x % y); 
  3.  const lcm = (x, y) => (x*y)/gcd(x, y)  
  4.  return arr.reduce((a,b) => lcm(a,b)); 
  5. // arrayLcm([1,2,3,4,5]) -> 60 
  6. // arrayLcm([4,8,12]) -> 24 
  1. ➜  code python 
  2. Python 3.6.4 (defaultDec 23 2017, 10:37:40) 
  3. [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin 
  4. Type "help""copyright""credits" or "license" for more information. 
  5. >>> import math 
  6. >>> arr = [1,2,3,4,5] 
  7. >>> size = 2 
  8. >>> for i in range(math.ceil(len(arr) / size)): 
  9. ...     print('index: ', i) 
  10. ... 
  11. index:  0 
  12. index:  1 
  13. index:  2 

应用 Array.reduce() 和 lcm 公式(应用递归)来计算一个数组的最大年夜公约数。

  1. ➜  code cat arrayGcd.js 
  2. const arrayGcd = arr => { 
  3.     const gcd = (x, y) => !y ? x : gcd(y, x % y); 
  4.     return arr.reduce((a, b) => gcd(a, b)); 
  5.  
  6. console.log(arrayGcd([1, 2, 3, 4, 5])); 
  7.  1/4    1 2 3 4 下一页 尾页

      推荐阅读

      NodeJs爬虫抓取古代典籍,共计16000个页面心得体会总结及项目分享

    【限时免费】岁尾最强一次云计算大年夜会,看传统、社区、互联网企业若何碰撞? 之前研究数据,零零碎散的写过一些数据抓取的爬虫,不过写的比较随便。有很多处所如今看起来并不是很合理 这>>>详细阅读


    本文标题:JavaScript30秒, 从入门到放弃

    地址:http://www.17bianji.com/lsqh/40136.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)