+ 1
I am not able to code conditionals in functions. Read the description for code link & problem description . Please Help
Actually , I want Javascript to take an input in the form of a no. (eg. 2) and output sum of squares of no.s from that no. till 1. (eg. input=2 , output=2^2+1^2.) so , my code asks for an input y , runs a function for squaring y , y-1 , y-2 , y-3 ... and sums these answers up to give the output. but , if the value which the function takes as an input becomes -ve then it assigns the ouput as 0 . But its not working. PLEASE HELP!!!! code link : https://code.sololearn.com/WWiGa5ycOq03/?ref=app
17 ответов
+ 13
var num = prompt("Input Num.")*1
function recursion(n) {
if(!n)return 0
return Math.pow(n,2)+recursion(n-1)
}
alert(recursion(num))
+ 13
@Bro Vfx
Calls again itself. On every call "n" is reduced by one and its square is added on sum stack.
+ 12
@Bro Vfx
it does, i tested it. do you get any errors or wrong output??
+ 12
2! is 2*1 ... not 3....
1+2+6
+ 11
@Bro Vfx
function factorial2(n) {
if(!n)return 0
return factorial(n)+factorial2(n-1)
}
function factorial(n) {
if(!n)return 0
return n+factorial(n-1)
}
alert(factorial2(prompt("Num")*1))
+ 9
@Bro Vfx
var num = prompt("Input Num.")*1
function recursion(n) {
if(!n)return 0
return factorial(n)+recursion(n-1)
}
function factorial(n) {
if(!n)return 1
return n*factorial(n-1)
}
alert(recursion(num))
//sorry for late response
+ 2
Rewrote it a bit:
function addns(x){
if(x<0){
return 0;
}
return x*x + addns(x-1);
}
var y = parseInt(prompt("no."));
var z = addns(y);
alert(z);
+ 2
thx guyz for this quick and perfect reply . Thx a lot
+ 2
@ValentinHacker I used to use |0 for int parsing, but parseInt is much more clear
+ 2
what does recursion function do ?
+ 1
can u tell how to code a function such as :
if input = 5
then output = ( 5! + 4! +3! +2! +1!)
+ 1
thx a lot , bro
+ 1
thx bro . you are a saviour
0
its not working
0
i tried .. when input=3 it results 9 . but acc to the condition 1! + 2! + 3! = 1+3+6=10
0
oh , its my mistake . Actually i meant addition factorial(2! = 1+2+3)
0
i made it and it worked . Then i wanted to extend it . I wanted a code for:-
example .- input = 3
output = 3!! + 2!! +1!! (3!! = 3! + 2! + 1! and same for other values)
i tried but its not working . here's the link : https://code.sololearn.com/WBP49Cf2CAj4/?ref=app
please check this out & make me aware of my mistake
TY