Skip to content

Instantly share code, notes, and snippets.

@arthur-flam
Last active October 17, 2023 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthur-flam/dfbe975b0d2cfb76da8fa1ea9648e4fe to your computer and use it in GitHub Desktop.
Save arthur-flam/dfbe975b0d2cfb76da8fa1ea9648e4fe to your computer and use it in GitHub Desktop.
constrexpr exponential function
// Adapted from an interview question that does the same with templates
// The goal was just to make the logic easier to understand with recent C++ features
// Don't use it in real-life LOL.
//
// It needs (1) a small wrapper to make the API cleaner (2) templates to work with any type...
// and in real-life you'll want more precision/speed/range/vectorization..........
//
// To check it's indeed compile time: https://godbolt.org -std=c++17
#include <iostream>
#include <utility>
constexpr std::pair<double, double> exp(double x, int n) {
if (n==0)
return std::pair<double, double>(1, 1);
return std::pair<double, double>(
exp(x, n-1).first * x / n,
exp(x, n-1).second + exp(x, n).first
);
}
int main() {
constexpr double x = 3;
constexpr int n = 10;
std::cout << exp(x, n).second << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment