C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_binomial_coefficient.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * ExprTk Binomial Coefficient (n-choose-r) *
6 * Author: Arash Partow (1999-2024) *
7 * URL: https://www.partow.net/programming/exprtk/index.html *
8 * *
9 * Copyright notice: *
10 * Free use of the Mathematical Expression Toolkit Library is *
11 * permitted under the guidelines and in accordance with the *
12 * most current version of the MIT License. *
13 * https://www.opensource.org/licenses/MIT *
14 * SPDX-License-Identifier: MIT *
15 * *
16 **************************************************************
17*/
18
19
20#include <cstdio>
21#include <string>
22
23#include "exprtk.hpp"
24
25
26template <typename T>
27inline T ncr_println(T n, T r, T ncr)
28{
29 printf("ncr(%2d,%2d) = %2llu\n",
30 static_cast<int>(n),
31 static_cast<int>(r),
32 static_cast<unsigned long long>(ncr));
33
34 return T(0);
35}
36
37template <typename T>
39{
40 typedef exprtk::symbol_table<T> symbol_table_t;
41 typedef exprtk::expression<T> expression_t;
42 typedef exprtk::parser<T> parser_t;
43 typedef exprtk::function_compositor<T> compositor_t;
44 typedef typename compositor_t::function function_t;
45
46 symbol_table_t symbol_table;
47 symbol_table.add_function("println",ncr_println);
48
49 compositor_t compositor(symbol_table);
50
51 // define function: ncr(n,r)
52 compositor.add(
53 function_t("ncr")
54 .vars("n", "r")
55 .expression
56 (
57 " switch "
58 " { "
59 " case n <= r : 1; "
60 " case r <= 0 : 1; "
61 " default : ncr(n - 1, r - 1) + "
62 " ncr(n - 1, r ) ; "
63 " } "
64 ));
65
66 const std::string ncr_program =
67 " var n := 25; "
68 " for (var r := 1; r < n; r += 1) "
69 " { "
70 " println(n, r, ncr(n,r)); "
71 " }; ";
72
73 expression_t expression;
74 expression.register_symbol_table(symbol_table);
75
76 parser_t parser;
77 parser.compile(ncr_program,expression);
78
79 expression.value();
80}
81
82int main()
83{
84 n_choose_r<double>();
85 return 0;
86}
T ncr_println(T n, T r, T ncr)