fork download
#include <array>

template<typename T, size_t N>
std::array<T,N> newton(const std::array<T,N> &xs, const std::array<T,N> &ys)
{
	std::array<T,N> as = ys;
	for (size_t k = 1; k < N; k++) {
		for (size_t j = N-1; j > k-1; j--) {
			as[j] = (as[j] - as[j-1]) / (xs[j] - xs[j-k]);
		}
	}
	return as;
}

int main()
{
	std::array<double, 4> xs = { 0.0, 1.0, -1.0, 2.0  }; 
	std::array<double, 4> ys = { 1.0, 5.0, -1.0, 17.0 }; // 1 + 2x + x^2 + x^3
	std::array<double, 4> as = newton(xs,ys);            // 1 + 4x + 1x(x-1) + 1x(x-1)(x+1)
	printf("%g %g %g %g\n", as[0], as[1], as[2], as[3]);
	return 0;
}
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
1 4 1 1