We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 7930a64 commit aae4038Copy full SHA for aae4038
series_sum/series_sum.php
@@ -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
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments