Changing div to lines with java script - javascript

The "output" div should be replaced with 10 lines of output. Each
line should display two numbers separated by a space. The first number should be the line number starting
with 1. So the numbers 1, 2, 3, 4... and so on. The second number should be the factorial of the line number.
(n factorial is 1 * 2 * 3 * ... * n.) That is, the numbers 1,
What should i use to create the list and to do the calculations. Tried using an array but was having difficulties in making the calculations. Any help would be appreciated

Check this one and try it
var result = '';
var lineno = 10;
for(j=1;j<=lineno;j++){
result = result + j + ' ' + fact(j) + '<br>';
}
document.getElementById("output").innerHTML = result;
function fact(n){
var i, no, fact;
f=1;
for(i=1; i<=n; i++)
{
f= f*i;
}
return f;
}
Link : https://jsfiddle.net/yrz46q85/

Counting factorial to 10 in 10 lines.
var output = document.getElementById("output");
var factorial = 1;
for(var i=1; i<=10; i++){
factorial = factorial * i;
output.innerHTML += i +". " + factorial + "</br>";
}
<div id="output"></div>

Related

Calculating sum of fractions in a loop

Implement a function fractionSum(n) that calculates and returns the sum of the following sequence:
1/n + 1/(n−1) + 1/(n−2) + ⋅⋅⋅ + 1/2 + 1
For example, fractionSum(5) calculates the following sum: 1/5+1/4+1/3+1/2+1
And then returns 2.283333333333333
I haven't even started writing function just yet since I'm still stuck at trying to figure out the right loop expression. This is what I've done so far:
var sum =0;
var fraction = 1;
var number = parseInt(prompt("Enter an integer: ", "5"));
for ( var counter = 0; counter <= number; counter++) {
fraction /= (number - counter); // do I need to declare parseFloat here for decimal# ?
sum += fraction;
}
document.write("The total value is " + sum);
The number doesn't match up at all from the example. I'm not sure what the problem is here.
I'm pretty confused right now. I know this is basic problem but I has tried multiple codes and it still didn't come out right.
Thank you so much
You're reusing the fraction from the previous iteration and dividing it by the next value. You need a new fraction instead:
fraction = 1 / (number - counter);
Also, you need the strict counter < number condition in the loop to avoid division by zero.
In the loop, counter must be less than number else at the end there will be divison by 0, the result will be infinity. Try this
let sum = 0;
let i = 0;
let num = parseInt(prompt("Enter an integer: ", "5"));
for(i; i < num; i++ ){
frac = 1 / ( num - i);
sum+= frac;
}
I figured it out. This is what I got:
<script>
function fractionSum(number) {
var sum =0;
for (var counter= 0 ; counter < number; counter++) {
sum += 1/(number - counter);
}
return sum;
}
var number = parseInt(prompt("Enter the value of n: ", "5"));
sum = fractionSum(number);
document.write("The fraction sum of order " + number + " is " + sum);
</script>
Thank you guys, it was very helpful

Ideas for how to catch the last index in a jscript for loop, where lengh of index is is unknown?

Consider the following for loop (and assuming we don't know 3 times table - i.e. how many results might occur).
<script summary>
function myFunction() {
var output_text = "";
var i;
for (i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if ("e.g. this is the last index?") {"e.g.then do this?"
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
}
</script>
Trying to 'output_text' as something like:
The number is 0
The number is 3
The number is 6
The number is 9
The number is 12
The number is 15
The number is the last 18
Any ideas for how to catch that last loop iteration.
This is just an example as actual application is a bit wordy - but the concept is the same.
I could run a count first to get index length, but wondered if there is an easier way.
Many thanks for anyone's time. Also first go at posting - any advice welcome.
Just add 3 to the current index and check if it exceeds 19.
function myFunction() {
var output_text = "";
var i;
const max = 19;
const factor = 3;
for (i = 0; i <= max; i++) {
if (i % factor === 0){
if (i + factor > max) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
return output_text;
}
document.write(myFunction());
If you have a number divisible by 3, perform a second check to see if 20 minus i < 3 and you'll know if it's the last number.
function myFunction() {
var output_text = "";
for (var i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if (20 - i < 3) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
document.getElementById("out").innerHTML = output_text;
}
myFunction();
<div id="out"></div>
The better approach is to show result of current iteration in the next iteration. In this case, last iteration will not be handled in the loop. So, you can handle it after easily.

beginner: rolling a dice: frequency and if-else-if?

How do I show the frequency with which each face of the dice finishes uppermost?
//this program stimulates rolling a dice
var outputAreaRef = document.getElementById("outputArea");
var array=[0, 1, 2, 3, 4, 5, 6];
var i=1;
var outString="";
while (i<60000)
{
var number=Math.floor((Math.random() * 6) + 1);
array[number]++;
i++;
}
outputAreaRef.innerHTML = " array: " + array ;
I see what you are trying to do and it may be easier to explain here.
You have a couple of issues. Your array should 6 in length, not 7 and all values MUST start with 0 or you will receive a false positive. If Zero is really One then you modify when you output, don't put it in your logic.
The method is correct to increment but the random number should be 0-5.Ultimately you could loop and output or use the console. Console is a far better way to check and debug your code than DOM injection.
If you don't know anything about it please take a look :-)
Chrome DevTools
var array=[0,0,0,0,0,0];
var i=1;
while (i<60000)
{
var number=Math.floor(Math.random()*6);
++array[number];
i++;
}
console.table(array)
It looks like you were just missing the output syntax. You'll need to output each index of your array, followed by its value. Try this:
//this program stimulates rolling a die
var outputAreaRef = document.getElementById("outputArea");
var array=[0, 1, 2, 3, 4, 5, 6];
var i=1;
var outString="";
while (i<60000)
{
var number=Math.floor((Math.random() * 6) + 1);
array[number]++;
i++;
}
for(var i = 0; i < array.length; i++)
{
outputAreaRef.innerHTML += i + ": " + array[i] +"<br />";
}
If what I think you're looking for is correct, then this will do it. I changed some of the code to my own preference of how to accomplish this, but the concepts are the same. If you keep using an array, then you can use forEach to iterate through it.
var array = { 1:0, 2:0, 3:0, 4:0, 5:0, 6:0 };
iterations = 60000;
for (var i = 0; i < iterations; i++)
{
var number=Math.floor((Math.random() * 6) + 1);
array[number]++;
}
document.getElementById("outputArea").innerHTML = " array: " + JSON.stringify(array) ;
for( var k in array ) {
array[k] = Math.round((array[k] / iterations) * 1000)/1000;
}
document.getElementById("frequencies").innerHTML = " array: " + JSON.stringify(array) ;
<div id="outputArea"></div>
<div id="frequencies"></div>

Creating a 'for' loop

I am trying to do an activity in my uni work and am having trouble getting the for loop to work. I have done the first stage using a while loop but I am getting stuck on the second stage.
My while loop -
var i=1;
while (i<=32) {
i = i*2;
document.writeln(+i +' ');
}
alert ('Wah-Lah!')
Your second part could be like that:
var sum = 0;
var k=1;
// 65 is too big !
for (i=1; i<30; i++)
{
sum += k;
k*=2;
document.writeln(+k +' ');
alert('Sum of all numbers = '+ sum);
document.writeln(' = ' + sum);
}
If you want to output the sum only, then you can just put the two lines, alert and doc.write outside the for loop
var sum = 0;
for (i=1; i<=64; i*=2) {
sum += i;
document.writeln(i);
}
document.writeln('sum: ' + sum);
You can modify your code the following way :
var sum=0;
for (i=1; i<65; i=i*2) {
sum += i;
document.writeln('' + i); //Displays values 1 2 4 8...
}
//Display Sum outside loop
document.writeln(' = ' + sum);
I'm not sure if I understand you well but in your for loop you are increasing you counter by 1, so in output you will get 1,2,3...,64. If you want to get output as 1,2,4,8... change your step argument to: i = i + 2. Finally your for loop should looks like:
for(i = 1; i < 65; i + 2)

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

Categories

Resources