C++ Mathematical Expression Toolkit (ExprTk) release
Loading...
Searching...
No Matches
Functions
exprtk_factorize_fermat.cpp File Reference
#include <cstdio>
#include <string>
#include "exprtk.hpp"
Include dependency graph for exprtk_factorize_fermat.cpp:

Go to the source code of this file.

Functions

template<typename T >
void factorize_fermats_method ()
 
int main ()
 

Function Documentation

◆ factorize_fermats_method()

template<typename T >
void factorize_fermats_method ( )

Definition at line 27 of file exprtk_factorize_fermat.cpp.

28{
29 typedef exprtk::symbol_table<T> symbol_table_t;
30 typedef exprtk::expression<T> expression_t;
31 typedef exprtk::parser<T> parser_t;
32 typedef exprtk::function_compositor<T> compositor_t;
33 typedef typename compositor_t::function function_t;
34
35 // Form: n = p*q where p,q are prime
36 T composites[] =
37 {
38 199203677, 779234623, 843093203, 883543291, 1197162971, 1282615157, 1368190717,
39 1552390397, 1765737859, 1800091571, 1878769589, 1993904873, 2257133471, 2520523529,
40 2579094799, 2853450949, 2935025369, 3095780533, 3164132249, 3408963511, 4260042859,
41 4608613981, 4654875857, 5085931997, 6064982771, 7278175081, 7289187463, 9206112101
42 };
43
45
46 symbol_table_t symbol_table;
47
48 symbol_table.add_vector ("composites", composites);
49 symbol_table.add_function("println" , println );
50
51 compositor_t compositor(symbol_table);
52
53 compositor.add(function_t()
54 .name("is_square")
55 .var("x")
56 .expression
57 (
58 " var s := sqrt(x); "
59 " var t := trunc(s); "
60 " (s - t) == 0; "
61 ));
62
63 compositor.add(function_t()
64 .name("fermat")
65 .var("n")
66 .expression
67 (
68 " if (n == 0) "
69 " { "
70 " return [0]; "
71 " } "
72 " else if ((n % 2) == 0) "
73 " { "
74 " return [n / 2]; "
75 " }; "
76 " "
77 " var a := ceil(sqrt(n)); "
78 " "
79 " while (not(is_square(a^2 - n))) "
80 " { "
81 " a += 1; "
82 " }; "
83 " "
84 " var b := sqrt(a^2 - n); "
85 " "
86 " a - b; "
87 ));
88
89 const std::string factorize_composites_program =
90 " for (var i := 0; i < composites[]; i += 1) "
91 " { "
92 " var n := composites[i]; "
93 " var factor0 := fermat(n); "
94 " var factor1 := n / factor0; "
95 " "
96 " if ((factor0 * factor1 == n) and (factor0 != 1)) "
97 " { "
98 " println('n: ', n, ' factors: { ', factor0 ,' , ', factor1 ,' } '); "
99 " } "
100 " else "
101 " { "
102 " println('failed to factorize ', n); "
103 " } "
104 " } "
105 " ";
106 expression_t expression;
107 expression.register_symbol_table(symbol_table);
108
109 parser_t parser;
110 parser.compile(factorize_composites_program,expression);
111
112 expression.value();
113}

◆ main()

int main ( )

Definition at line 115 of file exprtk_factorize_fermat.cpp.

116{
117 factorize_fermats_method<double>();
118 return 0;
119}