How do I write a generic memoize function?

后端 未结 15 1749
情话喂你
情话喂你 2020-12-09 05:25

I\'m writing a function to find triangle numbers and the natural way to write it is recursively:

function triangle (x)
   if x == 0 then return 0 end
   retu         


        
15条回答
  •  不知归路
    2020-12-09 06:21

    Recursion isn't necessary. The nth triangle number is n(n-1)/2, so...

    public int triangle(final int n){
       return n * (n - 1) / 2;
    }
    

提交回复
热议问题