LeetCode Count Primes
来源:互联网 发布:天津平山道淘宝城 编辑:程序博客网 时间:2024/05/16 18:34
Count Primes
Description:
Count the number of prime numbers less than a non-negative number, n
click to show more hints.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.:
思想:: 就是小于n的质数公约是只有1和本身,每一个小于n的数,非质数都是有(2,,4,3,5)的j倍,j=2,3,4.。。导致的。
把一个小于n的数字,里面(2,3,5)的j倍的数去掉,就是
把每一个数对应的一个数组,不是质数的变1, 最后遍历,看没有为1的个数,就是质数的个数。
我的解法
#include <stdio.h>#include <stdlib.h>int countPrimes(int n);int main(void){int n;scanf("%d",&n);printf("the answer is %d\n",countPrimes(n));return 0;}int countPrimes(int n) {int *p=(int *)calloc(n,sizeof(int));//申请了一个长度为n的数组,用p指向首地址for(int i=2; i*i<n; i++) {if(!*(p+i)){for(int j=i; i*j<n; j++) {*(p+i*j) = true;}}}int c=0;for(int i=2; i<n; i++) {//printf("the answer is %d\n",*(p+i) );if(*(p+i) == false)++c;}//free p;return c;}
其中使用了 calloc
malloc它允许从空间内存池中分配内存,malloc()的参数是一个指定所需字节数的整数.
例如:P=(int*)malloc(n*sizeof(int));
colloc与malloc类似,但是主要的区别是存储在已分配的内存空间中的值默认为0,使用malloc时,已分配的内存中可以是任意的值.
colloc需要两个参数,第一个是需要分配内存的变量的个数,第二个是每个变量的大小.
例如:P=(int*)colloc(n,colloc(int));
0 0
- LeetCode 204 - Count Primes
- [LeetCode] Count Primes
- LeetCode #Count Primes#
- 【leetcode】Count Primes
- LeetCode 204-Count Primes
- [LeetCode] Count Primes
- [LeetCode 204] Count Primes
- [LeetCode]Count Primes
- leetcode 204: Count Primes
- Count Primes Leetcode JAVA
- LeetCode OJ Count Primes
- [leetcode]Count Primes
- leetcode--Count Primes
- [LeetCode]Count Primes
- Count Primes LeetCode
- LeetCode (36) Count Primes
- LeetCode 204:Count Primes
- LeetCode:Count Primes
- 回调函数中删除对象引发的隐晦非法访问崩溃问题
- 5-18
- 5.8
- setInterval和clearInterval的使用
- 黑马程序员---Objective-C 内存管理 - set方法的内存管理
- LeetCode Count Primes
- Java时间格式转换大全
- linux shell
- DuiVision开发教程(9)-动态创建控件
- nginx日志管理
- mac下git与github简单使用
- 安卓创建接收短信发送短信
- p124 第三章 第45题 潘璠(未用递推)
- cocos2dx3.x的所有事件总结