Simple but pointless javascript

Associate
Joined
12 Jun 2003
Posts
898
Location
Wicklow, Ireland
hey i'm just learning javascript in college and our lecturer has given us some questions but there is one i'm totally stumped on.

i know the solution is VERY VERY simple but you know yourselves sometimes when the solution stare you in the face you still can get it.

here's the question

Write JavaScript that calculates the sum and product of all numbers from 1 to some user provided number. Print the results to the page.

so for the sum i was thinking something like this
bit of pseudocode:

Code:
number= ask user for it 
for(i = 0 ; i < number ; i++)
{
    sum += i ; 
}

for the product is where i'm getting stumped. is multiplying the numbers from 1 to n the same as n factorial? i'm clueless on how to implement this as i tuned out whilst factorial was covered as i don't see a major benefit of it.

any help is appreciated.
 
how about:

product = 1;

for (i = 1; i <= user number; i++){
product *= i;
}

println(product);

that should be ok i think, but i havent done javascript, just java. make sure you initialsie sum to 0 and product to 1. and yes the product he is asking is the same as factorial.
 
daven1986 said:
how about:

product = 1;

for (i = 1; i <= user number; i++){
product *= i;
}

println(product);

that should be ok i think, but i havent done javascript, just java. make sure you initialsie sum to 0 and product to 1. and yes the product he is asking is the same as factorial.
just make sure you change:
user number to user_number or something similar, so it's just one word!
 
Phnom_Penh said:
Sum = n(n+1)/2

For the product I'd do

for(i = 0 ; i < number ; i++)
{
product = product * i
}

yep, but if you use that, remember to star the "product" variable at 1, if you start at 0 it will go nowhere :)
 
Back
Top Bottom