JavaScript Just use javascript, dont include HTML Follow the instructions bellow
ID: 3876655 • 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 that is provided bellow, the other file should be called module.js that includes the function above. 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 Console for app.js:
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
module.js :
function calculateFibonacci(num) {
var a = 1,
b = 0,
temp;
while (num >= 0) {
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
// 1st method
function fibonacciSum(numOfFibonacciItems) {
var sumOfFibonacci = 0;
for(var i = 1; i <= numOfFibonacciItems; i++) {
sumOfFibonacci += calculateFibonacci(i); // calling function of app.js
}
console.log("Sum Of Fibonacci : "+sumOfFibonacci);
return sumOfFibonacci;
}
// 2nd method
function divideByRandom(sumOfFibonacci, maxRandomRange) {
var randomNumber = getRandomInt(maxRandomRange);
var afterDividing = sumOfFibonacci/randomNumber;
console.log("After dividing by random number : "+afterDividing);
return afterDividing;
}
// 3rd method
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
// this is required funtion
export function display(numOfFibonacciItems, maxRandomRange){
var sumOfFibonacci = fibonacciSum(numOfFibonacciItems);
var afterDividing = divideByRandom(sumOfFibonacci, maxRandomRange);
var fact = factorial(Math.floor(afterDividing));
console.log("Factorial : "+fact);
}
app.js :
import {display} from './module';
display(7,5);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.