File: fibonacci.cpp

package info (click to toggle)
boost1.90 1.90.0-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 593,120 kB
  • sloc: cpp: 4,190,908; xml: 196,648; python: 34,618; ansic: 23,145; asm: 5,468; sh: 3,774; makefile: 1,161; perl: 1,020; sql: 728; ruby: 676; yacc: 478; java: 77; lisp: 24; csh: 6
file content (58 lines) | stat: -rw-r--r-- 1,607 bytes parent folder | download | duplicates (21)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* Boost.Flyweight example of flyweight-based memoization.
 *
 * Copyright 2006-2008 Joaquin M Lopez Munoz.
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org/libs/flyweight for library home page.
 */

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

using namespace boost::flyweights;

/* Memoized calculation of Fibonacci numbers */

/* This class takes an int n and calculates F(n) at construction time */

struct compute_fibonacci;

/* A Fibonacci number can be modeled as a key-value flyweight
 * We choose the no_tracking policy so that the calculations
 * persist for future use throughout the program. See
 * Tutorial: Configuring Boost.Flyweight: Tracking policies for
 * further information on tracking policies.
 */

typedef flyweight<key_value<int,compute_fibonacci>,no_tracking> fibonacci;

/* Implementation of compute_fibonacci. Note that the construction
 * of compute_fibonacci(n) uses fibonacci(n-1) and fibonacci(n-2),
 * which effectively memoizes the computation.
 */

struct compute_fibonacci:private boost::noncopyable
{
  compute_fibonacci(int n):
    result(n==0?0:n==1?1:fibonacci(n-2).get()+fibonacci(n-1).get())
  {}

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

int main()
{
  /* list some Fibonacci numbers */

  for(int n=0;n<40;++n){
    std::cout<<"F("<<n<<")="<<fibonacci(n)<<std::endl;
  }

  return 0;
}