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

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

WBOY
Release: 2016-06-13 12:57:00
Original
888 people have browsed it

帮忙给写一个自然数求和函数,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);
Copy after login

------解决方案--------------------
function foo($n) {<br />
  return  $n*($n+1)/2;<br />
}<br />
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template