Calculating sum of fractions in a loop - javascript

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

Related

How to sum up all numbers entered in prompt

var num = prompt("Enter a number");
for (var sum = 0; sum <= num; sum++) {
sum = sum + 1;
}
document.write(sum);
example when I enter 6 in the prompt it will sum 1+2+3+4+5+6 =21. but as of right now i can only print 123456 instead of 21.
Input received by you is a string and that's why it's contacting rather than adding to sum.
This is the best optimum solution as its time complexity is O(3) times only.
so, it's fast. rather than with brute force which is o(n);
var num = prompt("Enter a number");
function total(n) {
return n * (n + 1) / 2;
}
document.write(total(parseInt(num)));
The problem with your code is that you're using sum for the loop and for the answer. That's messing everything up. You can use a variable for the loop and another variable for the sum.
Maybe that works for you.
var num = prompt("Enter a number");
var sum = 0;
for(var i = 1; i <= num; i++) {
sum += i;
}
document.write(sum);
here is some change in your code.
note: (+) is used to convert string-number type to number type
var num = prompt("Enter a number");
const sum = Array.from(Array(+num + 1).keys()).reduce((prev, curr) => prev += curr, 0);
document.write(sum);

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.

Changing div to lines with java script

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>

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/

JS probability of 10 people selecting the same number between 1 - 20

I'm pretty new to to javascript so please take it easy :)
I'm trying to figure out the probability of 10 people picking the same random number (1 - 20).
When I run the code it returns the same answer every time. I think something is wrong in the 3rd for loop when comparing numbers. Some help would be much appreciated, I've been stuck on this for 3 days now :(
var counter = 0;
//Determine probability (percentage)
for (var i = 1; i <=100; i++) {
//Create array with 10 elements and assign each element with random integer (1 - 20)
for (var j = 1; j <= 10; j++) {
var rndNum = [j];
rndNum = Math.random();
rndNum = Math.floor(rndNum * 20) + 1;
}
//Increment counter if match is found
for (var p1 = 1; p1 <= 9; p1++) {
for (var p2 = p1 + 1; p2 <= 10; p2++) {
if (rndNum[p1] == rndNum[p2]) {
counter++;
}
}
}
}
document.write("The probability of a match is: " + counter + "%");
Your code to make an "array" of random numbers is part of the problem. rndNum only has one value (it's an array with only one item in it, and you're overwriting it each time). You need array.push() to add values to an array.
You want something more like this:
var rndNum = [];
for (var j = 1; j <= 10; j++) {
rndNum.push(Math.floor(Math.random()* 20) + 1);
}
You want to know the probability that twenty people will pick the same random number?
alert("The probability of a match is: " + (Math.pow(.1, 20)*100)+ "%");
Or you want to know the probability that any two of twenty people will pick the same number?
alert("The probability of a match is: " + (Math.pow(.9, 20)*100)+ "%");
Your for loop should also start at 0, not one (the first element in an array is array[0]:
for (var p1 = 0; p1 <= 8; p1++) {
for (var p2 = p1 + 1; p2 <= 9; p2++) {
if (rndNum[p1] == rndNum[p2]) {
counter++;
}
}
}
You also need to divide your results by 10 because you have 1,000 tests (if you're checking to see if two match). If you want to see if they all match you would need something like:
var ordered = rndNum.sort();
if(ordered[0] == ordered[9])
counter2++;
Here's a fiddle of the combined array declaration and match checkers.

Categories

Resources