1.
Your task is to write a function which returns the sum of following series upto nth term(parameter).
Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...
Rules:
You need to round the answer to 2 decimal places and return it as String.
If the given value is 0 then it should return 0.00
You will only be given Natural Numbers as arguments.
Examples:
SeriesSum(1) => 1 = "1.00"
SeriesSum(2) => 1 + 1/4 = "1.25"
SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"
NOTE: In PHP the function is called series_sum().
代码:
function SeriesSum(n) {
for (var i = r=0; i < n; i++) {
r += 1 / (1 + i * 3);
}
return r.toFixed(2)
}
2
翁一,值钱五:鸡母一,值钱三:鸡雏三,值钱一。百钱买百鸡,问鸡翁、母、雏各几何?
这个还算简单:
function getN() {
var r=[];
for (var a = 0; a <= 20; a++) {
for (var b = 0, c = 0; b <= 33; b++) {
if (a * 5 + b * 3 + (100 - a - b) / 3 == 100) {
r.push([a,b,100-a-b])
}
}
}
return r
}
console.log(getN());
结果如下:
[ [ 0, 25, 75 ], [ 4, 18, 78 ], [ 8, 11, 81 ], [ 12, 4, 84 ] ]
3
填写运算符
在下面的算式中,添加"+"-" "、"x"、"/"4 个运算符,使等式成立。
5 5 5 5 5=5
算法分析:上述算式由5 个数字构成, 一共需要填入4 个运算符,并且每两个数字之间
的运算符有4 种选择,分别是"+"-"、"x"、"/"
代码:
function getOperator(){
var operators="+-*/";
l=operators.length;
for(var i= 0,r=[];i<l;i++){
for(var j=0;j<l;j++){
for(var h=0;j<l;j++){
for(var k=0;k<l;k++){
var jsonstr="5"+operators[i]+"5"+operators[j]+"5"+operators[h]+"5"+operators[k]+"5";
if(eval(jsonstr)===5){
console.log(jsonstr+"=5")
}
}
}
}
}
}
getOperator();
结果:
5+5-5+5-5=5
5-5+5+5-5=5
5-5-5+5+5=5
5-5*5+5*5=5
5-5/5+5/5=5
5*5/5+5-5=5
5/5*5+5-5=5
可是答案却是有很多种,我哪里错了?