[LeetCode][JavaScript]Count Primes
2016-02-28 15:53
567 查看
Count Prime
Description:Count the number of prime numbers less than a non-negative number, n.
https://leetcode.com/problems/count-primes/
找出所有小于n的数中的质数。
删数法。开一个1到n的数组,删除所有2的倍数,3的倍数...直到√n的倍数,最后剩下的就是质数。
/** * @param {number} n * @return {number} */ var countPrimes = function(n) { var count = 0, i, j, dict = [], len = Math.floor(Math.sqrt(n)); for(i = 2; i <= len; i++) for(j = 2; i * j <= n; j++) dict[i * j] = false; for(i = 2; i < n; i++) if(dict[i] === undefined) count++; return count; };
相关文章推荐
- eval在JS中的作用
- js setInterval和clearInterval 的使用
- JS闭包小结
- Jsonp 复习笔记
- JavaScript--map、reduce、filter、sort
- js中的各种宽高
- 解析JSON数据的详细步骤以及偷懒技巧(使用第三方库GSON以及GsonFormat工具)
- netctoss01_项目概述及规范【Servlet+JSP版】
- html、css、js的命名规范
- js继承学习
- jsp内置对象*response
- jsp内置对象*session
- jsp内置对象*out
- jsp内置对象*page
- jsp内置对象*exception
- jsp内置对象*pageContext
- jsp内置对象*config
- JavaScript--Map和Set介绍
- 【前端】Sublime text3 插件HTML/CSS/JS prettify 格式化代码
- bzoj 1031: [JSOI2007]字符加密Cipher 后缀数组