Home  >  Article  >  Backend Development  >  帮忙给写一个自然数求和函数,thanks!解决方案

帮忙给写一个自然数求和函数,thanks!解决方案

WBOY
WBOYOriginal
2016-06-13 11:11:00897browse

帮忙给写一个自然数求和函数,thanks!!!
如:向函数中带入3则经过函数的计算后结果为6(即1+2+3);向函数中带入6则经函数计算后结果为21(即1+2+2+4+5+6).


------解决方案--------------------
function foo($n){<br />    $ar=range(1,$n);<br />	return array_sum($ar);<br />}<br />echo foo(6);

------解决方案--------------------
function foo($n) {<br />  return  $n*($n+1)/2;<br />}<br />
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn