%!TEX pdflatex

\documentclass[french]{article}
\usepackage[margin=5mm]{geometry}
\usepackage{xintexpr,simplekv,amsmath}
\usepackage{codehigh}

\defKV[binomnewton]{%
	Indice=\def\binomnewtonindice{#1},%
	NbTermes=\def\binomnewtonnbtermes{#1}
}
\setKVdefault[binomnewton]{%
	Indice=k,%
	NbTermes={3},%
	Simplif=false,%
	Tout=false,%
	Enonce=true,%
	Somme=true,%
	Complet=false
}
\NewDocumentCommand\BinomeNewton{sO{}mmm}{%
	%étoilé = displaystyle
	%#2=clés
	%#3=a
	%#4=b
	%#5=n
	\restoreKV[binomnewton]%
	\setKV[binomnewton]{#2}%
	\ensuremath{%
		\IfBooleanT{#1}{\displaystyle}%
		\ifboolKV[binomnewton]{Enonce}%
			{%
				\left(#3+#4\right)^{#5}=%
			}%
			{}%
		\ifboolKV[binomnewton]{Somme}%
			{%
				\sum_{\binomnewtonindice=0}^{#5} \binom{#5}{\binomnewtonindice}{#3}^{\binomnewtonindice}{#4}^{#5-\binomnewtonindice}=%
			}%
			{}%
		\ifboolKV[binomnewton]{Tout}%
			{%
				\ifboolKV[binomnewton]{Complet}{\binom{#5}{0}}{}%
				{#3}^{#5}+%
				\xintFor* ##1 in {\xintSeq{1}{\xinteval{#5-1}}}\do{%
					\ifboolKV[binomnewton]{Simplif}%
						{\xinteval{binomial(#5,##1)}}%
						{\binom{#5}{##1}}%
					\xintifboolexpr{#5-##1 == 1}{{#3}}{{#3}^{\xinteval{#5-##1}}}%
					\xintifboolexpr{##1 == 1}{{#4}}{{#4}^{##1}}%
					+%
					}%
				\ifboolKV[binomnewton]{Complet}{\binom{#5}{#5}}{}%
				{#4}^{#5}%
			}%
			{%
				\ifboolKV[binomnewton]{Complet}{\binom{#5}{0}}{}%
				{#3}^{#5}\ifboolKV[binomnewton]{Complet}{{#4}^{0}}{}+%
				\xintFor* ##1 in {\xintSeq{1}{\xinteval{\binomnewtonnbtermes-1}}}\do{%
					\binom{#5}{##1}%
					{#3}^{#5-##1}%
					\ifboolKV[binomnewton]{Complet}{{#4}^{##1}}{\xintifboolexpr{##1 == 1}{{#4}}{{#4}^{##1}}}%
					+%
				}%
				\ldots+%
				\xintFor* ##1 in {\xintSeq{\xinteval{\binomnewtonnbtermes-1}}{1}}\do{%
					\binom{#5}{#5-##1}%
					\ifboolKV[binomnewton]{Complet}{{#3}^{##1}}{\xintifboolexpr{##1 == 1}{{#3}}{{#3}^{##1}}}%
					{#4}^{#5-##1}%
					+%
				}%
				\ifboolKV[binomnewton]{Complet}{\binom{#5}{#5}}{}%
				\ifboolKV[binomnewton]{Complet}{{#3}^{0}}{}{#4}^{#5}%
			}%
	}%
}

\begin{document}

\begin{demohigh}[language=latex/latex2]
\BinomeNewton{a}{b}{n}
\end{demohigh}

\begin{demohigh}[language=latex/latex2]
\BinomeNewton*[Complet]{a}{b}{n}
\end{demohigh}

\begin{demohigh}[language=latex/latex2]
\BinomeNewton*[Complet,NbTermes=2,Indice=i]{a}{b}{n}
\end{demohigh}

\begin{demohigh}[language=latex/latex2]
\BinomeNewton*[NbTermes=4,Somme=false]{x}{y}{u}
\end{demohigh}

\begin{demohigh}[language=latex/latex2]
\BinomeNewton*[Tout,Simplif]{a}{b}{5}
\end{demohigh}

\end{document}