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
原创粉丝点击