# Algorithm for parts integration

Sorry if this is a duplicate, I've searched how to do this to no avail.

What I'd like to do is a function that integrates by parts $n$ times, i.e

$$\int u(x) v(x) dx = u \left(\textstyle{\int}v\right) - \displaystyle{\int} u' \left(\textstyle{\int}v\right)dx$$ where $\textstyle{\int}v$ is the primitive of $v$.

I've done a very rustic function that does this,

parts[u_,v_]:=(#1 Integrate[#2,x] - Integrate[D[#1,x] Integrate[#2,x],x]&[u,v];


which performs well but, as you all can see has -at least- the mayor limitation that u and v should be given as functions of x.

At least it works, for example

In[1]=  parts[Exp[-x],1/x^2]
Out[1]= -Exp[-x]/x - ExpIntegralEi[-x]


The thing is, I'd like to tell parts to operate $n$ times, for example

\begin{align} \mbox{parts}\big(u,v,2\big) &= u v - \mbox{parts}\left(u',\textstyle{\int}v,1\right) \\ \\ \mbox{parts}\big(u(x),v(x),3\big) &= u(x)v(x) - u'\left(\textstyle{\int}v\right) + \mbox{parts}\big(u''(x),\textstyle{\iint}v,1\big) \end{align} and so on.

I hope my question is clear.

-

You can specify the cases for when $u$ and $v$ are free of variable.

ByParts[u_, v_, t_] :=
With[{w = Integrate[v, t]}, u w - Integrate[D[u, t] w, t]]
ByParts[u_, v_, t_] := u Integrate[v, t] /; FreeQ[u, t]
ByParts[u_, v_, t_] := v Integrate[u, t] /; FreeQ[v, t]

-

I think I can answer my question.

Mathematically, it makes sense to tell Mma which variable is the one to integrate by parts, like LaplaceTransform or D. Taking this into account, I redefine parts like this

parts[u_,v_,{x_,n_}]:= Sum[(-1)^m D[u,{x,m}] Nest[Integrate[#,x]&,v,m+1],{m,0,n-1}] +
(-1)^n Integrate[D[u,{x,n}] Nest[Integrate[#,x]&,v,n],x]


Again, I believe is rather amateurish, and I'd appreciate comments and other answers.

-
D[parts[u[x], v[x], {x, 3}], x] != u[x] v[x] – Hector Nov 15 '13 at 19:58
@Hector Right. I had an error on the last term. I hadn't multiplied it by $(-1)^n$. Besides that, I don't know why it behaves as you are pointing out. – Pragabhava Nov 15 '13 at 20:10
Great, you fixed it. – Hector Nov 15 '13 at 20:29