JavaScript Just use javascript, dont include HTML Follow the instructions bellow
ID: 3876419 • Letter: J
Question
JavaScript
Just use javascript, dont include HTML
Follow the instructions bellow for a good rate
Create a program that will display the result of three functions:
a) sum the elements from the Fibonacci sequence
b) divide them by randomly generated number
c) calculate factorial from the rounded result of previous operation
Functions should be stored in one, separate file. The main program should run from the app.js. Finally, a user should provide input for two variables - the number of Fibonacci items and the number responsible for the range of the randomly generated number from point b)
-----------------------------------------------------------------
Code for app.js is showen bellow:
app.js:
function calculateFibonacci(num) {
var a = 1,
b = 0,
temp;
while (num >= 0) {
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
function displayFibonacci(s) {
var result = "";
for (i = s; i > 0; i--) {
result += calculateFibonacci(i) + ", ";
}
return result.substring(0, result.length - 2);
}
console.log(displayFibonacci(21));
--------------------------------------------------------------------
Output in Console:
17711, 10946, 6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1
[Finished in 0.9s]
Explanation / Answer
The code will be
function calculateFibonacci(num) {
var a = 1,
b = 0,
temp;
while (num >= 0) {
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
function displayFibonacci(s) {
var result = "";
for (i = s; i > 0; i--) {
result += calculateFibonacci(i) + ", ";
}
return result.substring(0, result.length - 2);
}
function sum(n)
{
var sum=0;
while(n>0)
{
sum+=calculateFibonacci(n);
n--;
}
//this function returns the sum of n fibonnaci numbers
return sum;
}
function rand(n)
{
return n/Math.floor((Math.random() * 10) + 1);
//dividing by a random number between 1 and 10
//the function returns the Fibonnaci sum divided by a random number
}
function fact(n)
{
if(n==0 || n==1)
return 1;
else
return n*fact(n-1);
//this function is used to calculate the factorial
}
var a=sum(3);
var b=rand(a);
var c=fact(b);
// value for the argument of sum can be changed
print("Sum="+a+" "+" Random divison="+b+" "+" Factorial="+c);
The output is
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.