【leetcode】Count Primes

来源:互联网 发布:linux chown 777 编辑:程序博客网 时间:2024/05/23 11:26

【题目】

Description:

Count the number of prime numbers less than a non-negative number, n.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Hint:

Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less thann. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up ton would be O(n2). Could we do better?


【思路】

素数不能被比它小的整数整除, 建一个boolean 数组, 从2开始, 把其倍数小于N的都删掉.

注意 inner loop从i开始, 比i小的会在以前就被check过.


【代码】

O(n):Count the number of prime numbers less than a non-negative number, n

public class Solution {    public int countPrimes(int n) {        int res = 0;   //用来记录prime的个数        boolean[] used = new boolean[n]; //创建n大小的数组,用来记录数字有没有被标记的情况。        for (int i = 2; i <= Math.sqrt(n); i++) {  // i 从2 开始,到 Square(n)         if (!used[i]) { //只要i 这个地方仍旧是false:那么删除是这个数倍数 的 一切相关数字。            for( int j = i ; i *j <n;j++){                  used[i*j] = true;  //该数的倍数,都进行设置。              }           }        }//遍历一遍,数prime的个数。        for (int i = 2; i < n; i++) {         if (!used[i - 1]) {            res++;        }        }        return res;    }}

另一个种方法:

bitset不知道是个什么鬼

public int countPrimes(int n) {    BitSet bs = new BitSet(n);    bs.set(0); bs.set(1);    int ind = 0, count = 0;    while(ind < n){        ind = bs.nextClearBit(ind + 1);        if(ind >= n)            return count;        count++;        for(int i = 2 * ind; i < n; i += ind)            bs.set(i);    }    return count;}

(1)BitSet类
    大小可动态改变, 取值为true或false的位集合。用于表示一组布尔标志。   

此类实现了一个按需增长的位向量。位 set 的每个组件都有一个 boolean 值。用非负的整数将 BitSet 的位编入索引。可以对每个编入索引的位进行测试、设置或者清除。通过逻辑与、逻辑或和逻辑异或操作,可以使用一个 BitSet 修改另一个 BitSet 的内容。

默认情况下,set 中所有位的初始值都是 false。

  每个位 set 都有一个当前大小,也就是该位 set 当前所用空间的位数。注意,这个大小与位 set 的实现有关,所以它可能随实现的不同而更改。位 set 的长度与位 set 的逻辑长度有关,并且是与实现无关而定义的。

   除非另行说明,否则将 null 参数传递给 BitSet 中的任何方法都将导致 NullPointerException。 在没有外部同步的情况下,多个线程操作一个 BitSet 是不安全的。

(2) 构造函数: BitSet() or BitSet(int nbits)

(3) 一些方法 
public void set(int pos): 位置pos的字位设置为true。 
public void set(int bitIndex, boolean value) 将指定索引处的位设置为指定的值。 
public void clear(int pos): 位置pos的字位设置为false。
public void clear() : 将此 BitSet 中的所有位设置为 false。 
public int cardinality() 返回此 BitSet 中设置为 true 的位数。 
public boolean get(int pos): 返回位置是pos的字位值。 
public void and(BitSet other): other同该字位集进行与操作,结果作为该字位集的新值。 
public void or(BitSet other): other同该字位集进行或操作,结果作为该字位集的新值。 
public void xor(BitSet other): other同该字位集进行异或操作,结果作为该字位集的新值。
public void andNot(BitSet set) 清除此 BitSet 中所有的位,set - 用来屏蔽此 BitSet 的 BitSet
public int size(): 返回此 BitSet 表示位值时实际使用空间的位数。
public int length() 返回此 BitSet 的“逻辑大小”:BitSet 中最高设置位的索引加 1。 
public int hashCode(): 返回该集合Hash 码, 这个码同集合中的字位值有关。 
public boolean equals(Object other): 如果other中的字位同集合中的字位相同,返回true。 
public Object clone() 克隆此 BitSet,生成一个与之相等的新 BitSet。 
public String toString() 返回此位 set 的字符串表示形式。

例1:标明一个字符串中用了哪些字符
import java.util.BitSet;public class WhichChars{   private BitSet used = new BitSet();   public WhichChars(String str){      for(int i=0;i< str.length();i++)        used.set(str.charAt(i));  // set bit for char   }    public String toString(){         String desc="[";         int size=used.size();          for(int i=0;i< size;i++){             if(used.get(i))                 desc+=(char)i;            }             return desc+"]";         }    public static void main(String args[]){        WhichChars w=new WhichChars("How do you do");        System.out.println(w);    }   }
运行:
C:\work>java WhichChars

[ Hdouwy]

2. java.util.BitSet 研究(存数海量数据时的一个途径)

java.util.BitSet可以按位存储。
计算机中一个字节(byte)占8位(bit),我们java中数据至少按字节存储的,
比如一个int占4个字节。
如果遇到大的数据量,这样必然会需要很大存储空间和内存。
如何减少数据占用存储空间和内存可以用算法解决。
java.util.BitSet就提供了这样的算法。
比如有一堆数字,需要存储,source=[3,5,6,9]
用int就需要4*4个字节。
java.util.BitSet可以存true/false。
如果用java.util.BitSet,则会少很多,其原理是:
1,先找出数据中最大值maxvalue=9
2,声明一个BitSet bs,它的size是maxvalue+1=10
3,遍历数据source,bs[source[i]]设置成true.

最后的值是:
(0为false;1为true)
bs [0,0,0,1,0,1,1,0,0,1]
                3,   5,6,       9

这样一个本来要int型需要占4字节共32位的数字现在只用了1位!
比例32:1  

这样就省下了很大空间。

 

 

看看测试例子

[html] view plaincopy
  1. package com;  
  2.   
  3. import java.util.BitSet;  
  4.   
  5. public class MainTestThree {  
  6.   
  7.     /**  
  8.      * @param args  
  9.      */  
  10.     public static void main(String[] args) {  
  11.         BitSet bm=new BitSet();  
  12.         System.out.println(bm.isEmpty()+"--"+bm.size());  
  13.         bm.set(0);  
  14.         System.out.println(bm.isEmpty()+"--"+bm.size());  
  15.         bm.set(1);  
  16.         System.out.println(bm.isEmpty()+"--"+bm.size());  
  17.         System.out.println(bm.get(65));  
  18.         System.out.println(bm.isEmpty()+"--"+bm.size());  
  19.         bm.set(65);  
  20.         System.out.println(bm.isEmpty()+"--"+bm.size());  
  21.     }  
  22.   
  23. }  

 输出:
 true--64
false--64
false--64
false
false--64
false--128
 
说明默认的构造函数声明一个64位的BitSet,值都是false。
如果你要用的位超过了默认size,它会再申请64位,而不是报错。

[html] view plaincopy
  1. package com;  
  2.   
  3. import java.util.BitSet;  
  4.   
  5. public class MianTestFour {  
  6.   
  7.     /**  
  8.      * @param args  
  9.      */  
  10.     public static void main(String[] args) {  
  11.         BitSet bm1=new BitSet(7);  
  12.         System.out.println(bm1.isEmpty()+"--"+bm1.size());  
  13.           
  14.         BitSet bm2=new BitSet(63);  
  15.         System.out.println(bm2.isEmpty()+"--"+bm2.size());  
  16.           
  17.         BitSet bm3=new BitSet(65);  
  18.         System.out.println(bm3.isEmpty()+"--"+bm3.size());  
  19.           
  20.         BitSet bm4=new BitSet(111);  
  21.         System.out.println(bm4.isEmpty()+"--"+bm4.size());  
  22.     }  
  23.   
  24. }  


 

输出:
true--64
true--64
true--128
true--128

说明你申请的位都是以64为倍数的,就是说你申请不超过一个64的就按64算,超过一个不超过
2个的就按128算。

 

[html] view plaincopy
  1. package com;  
  2.   
  3. import java.util.BitSet;  
  4.   
  5. public class MainTestFive {  
  6.   
  7.     /**  
  8.      * @param args  
  9.      */  
  10.     public static void main(String[] args) {  
  11.         int[] shu={2,42,5,6,6,18,33,15,25,31,28,37};  
  12.         BitSet bm1=new BitSet(MainTestFive.getMaxValue(shu));  
  13.         System.out.println("bm1.size()--"+bm1.size());  
  14.           
  15.         MainTestFive.putValueIntoBitSet(shu, bm1);  
  16.         printBitSet(bm1);  
  17.     }  
  18.       
  19.     //初始全部为false,这个你可以不用,因为默认都是false  
  20.     public static void initBitSet(BitSet bs){  
  21.         for(int i=0;i<bs.size();i++){  
  22.             bs.set(i, false);  
  23.         }  
  24.     }  
  25.     //打印  
  26.     public static void printBitSet(BitSet bs){  
  27.         StringBuffer buf=new StringBuffer();  
  28.         buf.append("[\n");  
  29.         for(int i=0;i<bs.size();i++){  
  30.             if(i<bs.size()-1){  
  31.                 buf.append(MainTestFive.getBitTo10(bs.get(i))+",");  
  32.             }else{  
  33.                 buf.append(MainTestFive.getBitTo10(bs.get(i)));  
  34.             }  
  35.             if((i+1)%8==0&&i!=0){  
  36.                 buf.append("\n");  
  37.             }  
  38.         }  
  39.         buf.append("]");  
  40.         System.out.println(buf.toString());  
  41.     }  
  42.     //找出数据集合最大值  
  43.     public static int getMaxValue(int[] zu){  
  44.         int temp=0;  
  45.         temp=zu[0];  
  46.         for(int i=0;i<zu.length;i++){  
  47.             if(temp<zu[i]){  
  48.                 temp=zu[i];  
  49.             }  
  50.         }  
  51.         System.out.println("maxvalue:"+temp);  
  52.         return temp;  
  53.     }  
  54.     //放值  
  55.     public static void putValueIntoBitSet(int[] shu,BitSet bs){  
  56.         for(int i=0;i<shu.length;i++){  
  57.             bs.set(shu[i], true);  
  58.         }  
  59.     }  
  60.     //true,false换成1,0为了好看  
  61.     public static String getBitTo10(boolean flag){  
  62.         String a="";  
  63.         if(flag==true){  
  64.             return "1";  
  65.         }else{  
  66.             return "0";  
  67.         }  
  68.     }  
  69.   
  70. }  


 


输出:
maxvalue:42
bm1.size()--64
[
0,0,1,0,0,1,1,0,
0,0,0,0,0,0,0,1,
0,0,1,0,0,0,0,0,
0,1,0,0,1,0,0,1,
0,1,0,0,0,1,0,0,
0,0,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0
]

这样便完成了存值和取值。
注意它会对重复的数字过滤,就是说,一个数字出现过超过2次的它都记成1.

出现的次数这个信息就丢了



0 0