1/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2
3/*
4 Copyright (C) 2003 Ferdinando Ametrano
5
6 This file is part of QuantLib, a free-software/open-source library
7 for financial quantitative analysts and developers - http://quantlib.org/
8
9 QuantLib is free software: you can redistribute it and/or modify it
10 under the terms of the QuantLib license. You should have received a
11 copy of the license along with this program; if not, please email
12 <quantlib-dev@lists.sf.net>. The license is also available online at
13 <http://quantlib.org/license.shtml>.
14
15 This program is distributed in the hope that it will be useful, but WITHOUT
16 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 FOR A PARTICULAR PURPOSE. See the license for more details.
18*/
19
20// ===========================================================================
21// NOTE: The following copyright notice applies to the original code,
22//
23// Copyright (C) 2002 Peter Jäckel "Monte Carlo Methods in Finance".
24// All rights reserved.
25//
26// Permission to use, copy, modify, and distribute this software is freely
27// granted, provided that this notice is preserved.
28// ===========================================================================
29
30#include <ql/math/primenumbers.hpp>
31#include <iterator>
32
33namespace QuantLib {
34
35 namespace {
36
37 const BigNatural firstPrimes[] = {
38 // the first two primes are mandatory for bootstrapping
39 2, 3,
40 // optional additional precomputed primes
41 5, 7, 11, 13, 17, 19, 23, 29,
42 31, 37, 41, 43, 47 };
43 }
44
45 std::vector<BigNatural> PrimeNumbers::primeNumbers_;
46
47 BigNatural PrimeNumbers::get(Size absoluteIndex) {
48 if (primeNumbers_.empty()) {
49 Size n = sizeof(firstPrimes)/sizeof(firstPrimes[0]);
50 primeNumbers_.insert(position: primeNumbers_.end(),
51 first: firstPrimes, last: firstPrimes+n);
52 }
53 while (primeNumbers_.size()<=absoluteIndex)
54 nextPrimeNumber();
55 return primeNumbers_[absoluteIndex];
56 }
57
58 BigNatural PrimeNumbers::nextPrimeNumber() {
59 BigNatural p, n, m = primeNumbers_.back();
60 do {
61 // skip the even numbers
62 m += 2;
63 n = static_cast<BigNatural>(std::sqrt(x: Real(m)));
64 // i=1 since the even numbers have already been skipped
65 Size i = 1;
66 do {
67 p = primeNumbers_[i];
68 ++i;
69 } while (((m % p) != 0U) && p <= n);
70 } while ( p<=n );
71 primeNumbers_.push_back(x: m);
72 return m;
73 }
74
75}
76

source code of quantlib/ql/math/primenumbers.cpp

Morty Proxy This is a proxified and sanitized view of the page, visit original site.