Skip to content

Instantly share code, notes, and snippets.

@falcon8823
Created October 3, 2010 14:07
Show Gist options
  • Save falcon8823/608597 to your computer and use it in GitHub Desktop.
Save falcon8823/608597 to your computer and use it in GitHub Desktop.
#include <math.h>
#include <iostream>
#include <fstream>
class Bit{
public:
unsigned char GetBit(unsigned long pos);
void ResetBit(unsigned long pos);
void SetBit(unsigned long pos);
void ReverseBit(unsigned long pos);
void SetSize(unsigned long size);
unsigned long GetSize();
Bit();
virtual ~Bit();
protected:
unsigned char *m_data;
unsigned long m_size;
};
void OutPut2File(Bit*, unsigned long long int, unsigned long long int);
using namespace std;
#define FILECUT 10
int main(void)
{
unsigned long long int Max, NoteMax, n, i;
Bit *Note;
Note = new Bit;
cout << "Max of Prime Number:";
cin >> Max;
if(Max % 2 != 0)
Max++;
NoteMax = (Max / 2) - 1;
Note -> SetSize(NoteMax);
/* 配列ノート作成ループ */
for(n = 0; n <= NoteMax - 1; n++) {
Note->SetBit(n);
}
cout << "Now calculating..." << endl;
/* 素数判定ループ */
for(n = 0; 2 * n + 3 <= sqrt(Max); n++) {
if(Note->GetBit(n) == 1) {
for(i = 3; (2 * n + 3) * i <= Max; i += 2)
Note->ResetBit((((2 * n + 3) * i) - 3) / 2);
}
}
cout << "Now putting out data..." << endl;
OutPut2File(Note, Max, NoteMax);
delete Note;
return 0;
}
void OutPut2File(Bit *Note, unsigned long long int Max, unsigned long long int NoteMax)
{
ofstream output_file("prime_list.txt");
/* 出力処理 */
output_file << "2 ";
int SCount = 1;//素数カウント変数
int FCount = 1;//列数カウント変数
unsigned long long int i;
for (i = 0; i <= NoteMax; i++) {
if(Note->GetBit(i) == 1) {
FCount++;//列数カウント
SCount++;//素数カウント
output_file << (2 * i) + 3;
/* 列数が定数に一致したら、カウントリセット。 */
if (FCount == FILECUT) {
output_file << endl;
FCount = 0;
}
else output_file << " ";
}
}
output_file << "\n\n" << "2から" << Max << "までの素数の個数:" << SCount << endl;
}
// 構築/消滅
Bit::Bit()
{
SetSize(1);
}
Bit::~Bit()
{
delete [] m_data;
}
// サイズの設定
void Bit::SetSize(unsigned long size)
{
if (size==0) return;
delete [] m_data;
m_size = size;
m_data = new unsigned char [(size + 7) >> 3];
}
// サイズの取得
unsigned long Bit::GetSize()
{
return m_size;
}
// ビットを1にする
void Bit::SetBit(unsigned long pos)
{
if (pos>=m_size) return; // 範囲外
m_data[pos>>3] |= 1 << (pos % 8);
}
// ビットを0にする
void Bit::ResetBit(unsigned long pos)
{
if (pos>=m_size) return; // 範囲外
m_data[pos>>3] &= ~(1 << (pos % 8));
}
// ビットを反転する
void Bit::ReverseBit(unsigned long pos)
{
if (pos>=m_size) return; // 範囲外
m_data[pos>>3] ^= 1 << (pos % 8);
}
// ビットを取得する
unsigned char Bit::GetBit(unsigned long pos)
{
if (pos>=m_size) return 2; // 範囲外
return (m_data[pos >> 3] >> (pos&7))&1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment