template functions N2 to o(N)

Signed-off-by: aLekSer <gdocse@gmail.com>