Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit aae4038

Browse files
author
uuk020
committed
找规律计算 series_sum
1 parent 7930a64 commit aae4038

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

‎series_sum/series_sum.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
/**
3+
* 规律计算题
4+
* Your task is to write a function which returns the sum of following series upto nth term(parameter).
5+
* Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
6+
* You need to round the answer to 2 decimal places and return it as String.
7+
* If the given value is 0 then it should return 0.00
8+
* You will only be given Natural Numbers as arguments.
9+
*/
10+
function series_sum($n)
11+
{
12+
// Your code here
13+
$offset = 1;
14+
if (!is_int($n)) {
15+
return '$n is not int';
16+
}
17+
if ($n === 0) {
18+
return 0.00;
19+
}
20+
for ($i = 0; $i < $n; $i++) {
21+
$sum += 1 / $offset;
22+
// 规律: 4 7 10..每次除于的数都是上个数+3
23+
$offset += 3;
24+
}
25+
return round($sum, 2);
26+
}
27+
28+
function series_sum_clever($n)
29+
{
30+
$sum = 0;
31+
for($i=0; $i<$n; $i++) {
32+
//结合循环$i 计算每次要除于的数.为$i的值*3+1得出
33+
$sum += 1/(1+3*$i);
34+
}
35+
return round($sum,2);
36+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /