DGtal  0.9.3beta
convergents.cpp
1 
14 #include <iostream>
17 #include "DGtal/arithmetic/LighterSternBrocot.h"
19 
21 
22 using namespace DGtal;
23 
25 
26 void usage( int, char** argv )
27 {
28  std::cerr << "Usage: " << argv[ 0 ] << " <p> <q>" << std::endl;
29  std::cerr << "\t - computes the successive convergent of the fraction p / q." << std::endl;
30 }
31 
35 int main( int argc, char** argv )
36 {
37  if ( argc < 3 )
38  {
39  usage( argc, argv );
40  return 1;
41  }
42 
44  typedef LighterSternBrocot<DGtal::int64_t, DGtal::int64_t, StdMapRebinder> SB; // the type of the Stern-Brocot tree
45  typedef SB::Fraction Fraction; // the type for fractions
46  typedef Fraction::ConstIterator ConstIterator; // the iterator type for visiting quotients
47  typedef Fraction::Value Value; // the value of the iterator, a pair (quotient,depth).
49 
51  DGtal::int64_t p = atoll( argv[ 1 ] );
52  DGtal::int64_t q = atoll( argv[ 2 ] );
53  Fraction f( p, q ); // fraction p/q
55 
57  // Visit quotients u_k as pair (u_k,k)
58  std::cout << "z = ";
59  ConstIterator itbegin = f.begin(), itend = f.end();
60  for ( ConstIterator it = itbegin; it != itend; ++it )
61  {
62  Value u = *it;
63  std::cout << ( ( it == itbegin ) ? "[" : "," )
64  << u.first;
65  }
66  std::cout << "]" << std::endl;
68 
70  Fraction g; // fraction null, 0/0, invalid
71  for ( ConstIterator it = itbegin; it != itend; ++it )
72  {
73  Value u = *it;
74  std::cout << "z_" << u.second << " = ";
75  g.push_back( u ); // add (u_i,i) to existing fractions
76  std::cout << g.p() << " / " << g.q() << std::endl;
77  }
79  return 0;
80 }
81 
DGtal is the top-level namespace which contains all DGtal functions and types.
Aim: The Stern-Brocot tree is the tree of irreducible fractions. This class allows to construct it pr...
boost::int64_t int64_t
signed 94-bit integer.
Definition: BasicTypes.h:74