1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Boost.Flyweightで素数生成

Last updated at Posted at 2014-01-31

#Boost.Flyweight
Boost.Flyweightは所謂Flyweightパターンを簡単に実装出来る便利なライブラリである。
今回はそのチュートリアルの1つkey-value flyweightsをお手本に素数生成した。

#コード


#include "stdafx.h"
#include<iostream>
#include<boost/flyweight.hpp>
#include<boost/flyweight/key_value.hpp>
#include<boost/flyweight/no_tracking.hpp>
#include<boost/noncopyable.hpp>

class compute_prime;
int gen_prime(int);

typedef boost::flyweight<boost::flyweights::key_value<int, compute_prime>, boost::flyweights::no_tracking> prime;

class compute_prime : private boost::noncopyable{
public:
	compute_prime(int n):
		result(gen_prime(n))
	{}

	operator int() const{
		return result;
	}
	int result;
};

int gen_prime(int n){
	if (n == 0){
		return 2;
	}
	int p = prime(n - 1).get() + 1;
	while (true){
		int i = 0;
		while (true){
			if (prime(i).get() > sqrt(p)){
				return p;
			}
			if (p % prime(i).get() == 0){
				break;
			}
			++i;
		}
		++p;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	//スタックオーバーフローを防ぐ^^;;
	for (int i = 0; i < 10000; ++i){
		prime(i).get();
	}

	std::cout << prime(10000);
	return 0;
}

#感想
いきなり大きな素数を求めようとするとスタックオーバーフローが起こる。再帰にすべきじゃなかった。
既に求めた最大の素数を記録さえしとけばスタックオーバーフロー自体は防げる。どこに持たせるのがお行儀が良いだろうか。

1
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?