最近在看C#程式設計的教材,唐大仕的。
第三章的第二節例3-6用BitArray來實作計算從1到給定最大資料間素數個數。我愣是沒看懂其演算法。主要糾結在class BitArray的定義:
using System;
class BitArray
{
int[] bits;
int length;
public BitArray(int length){
if(length <0) throw new ArgumentException();
bits = new int[((length - 1) >> 5) + 1];
this.length = length;
}
public int Length{
get{return length;
}
public bool this[index]{
get{
if(index < 0 || index >= length){
throw new IndexOutOfRangeException();
}
return (bits[index >> 5] & 1 << index) != 0;
}
set{
if(index < 0 || index >= length){
throw new IndexOutOfRangeException();
}
if(value){
bits[index >> 5] |= 1 << index;
}
else{
bits[index >> 5] &= ~(1 << index);
}
}
}
}
還好理解,定義一個指定大小的int陣列。但后面的
bits = new int[((length - 1) >> 5) + 1];
就有點讓我眩暈了。
public bool this[index]{
get{
if(index < 0 || index >= length){
throw new IndexOutOfRangeException();
}
return (bits[index >> 5] & 1 << index) != 0;
}
set{
if(index < 0 || index >= length){
throw new IndexOutOfRangeException();
}
if(value){
bits[index >> 5] |= 1 << index;
}
else{
bits[index >> 5] &= ~(1 << index);
}
}
}
bits[index >> 5] |= 1 << index;以及
bits[index >> 5] &= ~(1 << index);的每個運算子都認識,這最后會得到什么結果越來越迷惑。
尤其是這
index >> 5和
1 << index,當著index>32的時候,這
1 << index是如何操作的?
望高手答復,多謝!
uj5u.com熱心網友回復:
貼出“計算從1到給定最大資料間素數個數”的代碼。斷章取以的代碼沒用。uj5u.com熱心網友回復:
既然認得 << ,那為何不知道<< 就是*2uj5u.com熱心網友回復:
大致可以認為,代碼的作者打算使用篩法,也就是首先把100個都標記為1,再分別把2、3、5。。。的倍數洗掉,剩下的就是質數uj5u.com熱心網友回復:
class CountPrimes
{
static int Count(int max){
BitArray flags = new BitArray(max + 1);
int count = 1;
for(int i = 2; i <= max; i ++){
if(!flags[i]){
for(int j = i * 2; j <= max; j += i)
flags[j] = true;
count ++;
}
}
return count;
}
static void main(){
Consol.Write("請輸入一個數:");
string s = Console.ReadLine();
int max = int.Parse(s);
int count = Count(max);
Console.WriteLine("在1與{0}找到{1}個素數",max,count);
}
}
uj5u.com熱心網友回復:
這就是啥埃拉托斯特尼篩法求素數吧。可以先了解下這種方法的原理,然后再去了解他每一步的代碼為什么要這樣寫。uj5u.com熱心網友回復:
貼出“計算從1到給定最大資料間素數個數”的代碼。斷章取以的代碼沒用。uj5u.com熱心網友回復:
大致可以認為,代碼的作者打算使用篩法,也就是首先把100個都標記為1,再分別把2、3、5。。。的倍數洗掉,剩下的就是質數轉載請註明出處,本文鏈接:https://www.uj5u.com/net/13007.html
標籤:C#
