C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
exprtk_gcd.cpp
Go to the documentation of this file.
1/*
2 **************************************************************
3 * C++ Mathematical Expression Toolkit Library *
4 * *
5 * ExprTk Greatest Common Divisor Example *
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>
27T gcd_println(T x, T y, T z)
28{
29 printf("gcd(%2d,%2d) = %2d\n",
30 static_cast<int>(x),
31 static_cast<int>(y),
32 static_cast<int>(z));
33
34 return T(0);
35}
36
37template <typename T>
38void gcd()
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",gcd_println);
48
49 compositor_t compositor(symbol_table);
50
51 // define function: gcd(x,y)
52 compositor.add(
53 function_t("gcd")
54 .vars("x","y")
55 .expression
56 (
57 " switch "
58 " { "
59 " case 0 = x : 0; "
60 " case 0 = y : x; "
61 " case x = y : x; "
62 " case x > y : gcd(x - y, y); "
63 " default : gcd(x, y - x); "
64 " } "
65 ));
66
67 const std::string gcd_program =
68 " i := 0; "
69 " while ((i += 1) < 100) "
70 " { "
71 " j := 0; "
72 " repeat "
73 " println(i, j, gcd(i,j)); "
74 " until ((j += 1) >= 100); "
75 " }; ";
76
77 expression_t expression;
78 expression.register_symbol_table(symbol_table);
79
80 parser_t parser;
81 parser.enable_unknown_symbol_resolver();
82 parser.compile(gcd_program,expression);
83
84 expression.value();
85}
86
87int main()
88{
89 gcd<double>();
90 return 0;
91}
void gcd()
T gcd_println(T x, T y, T z)
int main()