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);
Related
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
I am trying to run a program that, upon receiving a positive integer, splits it into its separate digits like so. Number is 652, output is 2, 5, 6. There is supposed to no arrays and I can't make the number a string. I've written most of the code but it's missing something that I can't figure out. The issue is really that I don't know how to store the numbers to be output during iterations. Would appreciate any help. I am using a while loop but for loop could be used as well.
function problem_09() {
var outputObj=document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
var i = 0;
var digits = ;
outputObj.innerHTML="number: "+a+"<br><br>its digits: ";
while (a>0) {
digits[i]= a%10;
a = Math.floor(a/10);
i++;
}
outputObj.innerHTML=digits;
outputObj.innerHTML=outputObj.innerHTML+"<br><br>"+"program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
I know the issue lies with the digits and the i but I don't know how to fix it.
You could take a place value and multiply by 10 for each iteration.
function getDigits(value) {
var place = 1;
while (value >= place) {
console.log(Math.floor(value / place) % 10);
place *= 10;
}
}
getDigits(652);
getDigits(100);
A solution without using Math.floor(...)
function getDigits(n) {
var res = [];
while (n > 0) {
var r = n % 10,
d = n - r,
curr = d / 10;
n = curr;
res.push(r);
}
return res;
}
var n = prompt("Enter a number: "),
output = document.getElementById("output");
output.textContent = getDigits(+n);
<div id="output"></div>
then just to replace
var i = 0;
var digits = [];
while (a > 0) {
digits.push(a % 10);
a = Math.floor(a/10);
i++;
}
the question does not make really sense.. without arrays, but he is actually expecting the result to be an array...
I would like to sum the given factorials numbers in javascript
'1! + 2! + 3! + ... + n!'
You may use factorial function :
Iterative function:
function sFact(num)
{
var rval=1;
for (var i = 2; i <= num; i++)
rval = rval * i;
return rval;
}
Recursive
function rFact(num)
{
if (num === 0)
{ return 1; }
else
{ return num * rFact( num - 1 ); }
}
I copied these function from this link.
Now what can you do is.
Suppose n value is 6.
var n = 6;
var sum = 0;
for(var i=1;i<=n;i++)
{
sum = sum + rFact(i);//Here you can use one of factorial funciton. I am using recursive function
}
document.print("The answer is "+ sum );
The naïve solution would be to actually calculate every factorial and add them together, which has a complexity of O(n²). However, if you're clever, you can design an algorithm that solves the same problem with a complexity of O(n). Take a look at the pattern of the following example that calculates the sum of the factorials of 1 through 4.
1!+2!+3!+4! =
1+1*2+1*2*3+1*2*3*4
Notice how you're reusing results from previous calculations multiple times? This can be taken advantage of. You can calculate the sum of all the factorials up to n with a program something like this.
function sumFactorials(n) {
var sum = 0;
var prod = 1;
for(var i=1; i<=n; i++) {
prod *= i;
sum += prod;
}
return sum;
}
What I'm trying to do can be easily illustrated with an example. Assume the following:
var minNum = 1;
var maxNum = 30;
var sum = 75;
var amount = 6;
I want to get all the permutations of amount numbers that add up to sum and are >= minNum && <= maxNum.
For example, if I was to create these permutations by hand, I would start like this:
30,30,12,1,1,1
30,30,11,2,1,1
30,30,11,1,2,1
30,30,11,1,1,2
30,30,10,3,1,1
30,30,10,2,2,1
etc
Is this a known problem in mathematics/programming and are there any algorithms that solve it?
Thanks in advance.
Here's a JavaScript solution (if your environment recursion depth limits the number of results you would like, you can convert the recursion to an explicit array-stack, push the arguments as would a function call and pop to process them):
function partition(n, min, max, parts) {
if (n < 0){
return;
} else if (n == 0) {
document.getElementById('output').innerHTML += (JSON.stringify(parts)) + '<br>';
} else {
for (var i=max; i>=min; i--){
var _parts = parts.slice();
_parts.push(i);
partition(n-i,min,max,_parts)
}
}
}
partition(6,2,4,[])
<pre id="output"></pre>
What is the most efficient way to write a javascript loop to calculate the number of occurrences of 7's (as an example number) that will be encountered in counting from 1 to 100?
Example:
function numberOccurences(targetNumber, minNumber, maxNumber) {
var count = 0;
for (i = minNumber; i < maxNumber; i++) {
count = count + (i.toString().split(targetNumber).length - 1);
}
return count;
}
var result = numberOccurences(7,1,100);
This will do it without looking at the actual numbers. Sorry, no loop, but you did ask for effeciency. If you really want to use a loop, make the recursion an iteration.
function digitOccurences(digit, min, max, base) {
if (typeof base != "number") base = 10;
return digitOccurencesPlus(digit, max, base, 1, 0) - digitOccurencesPlus(digit, min, base, 1, 0);
function digitOccurencesPlus(digit, N, base, pow, rest) {
if (N == 0) return 0;
var lastDigit = N%base,
prevDigits = (N-lastDigit)/base;
var occsInLastDigit = pow*(prevDigits+(lastDigit>digit));
var occsOfLastInRest = rest * (lastDigit==digit);
// console.log(prevDigits+" "+lastDigit, rest, occsInLastDigit, occsOfLastInRest);
return occsInLastDigit + occsOfLastInRest + digitOccurencesPlus(digit, prevDigits, base, pow*base, pow*lastDigit+rest);
}
}
This is an interesting problem, and already has similar answers for other languages. Maybe you could try to make this one in javascript: Count the number of Ks between 0 and N
That solution is for occurences from 0 to n, but you could easily use it to calculate from a to b this way:
occurences(a,b)= occurences(0,b)-occurences(0,a)
This is much faster (x6) than my original function...JSPERF
function numberOccurences2(targetNumber, minNumber, maxNumber) {
var strMe = "";
for (i = minNumber; i < maxNumber; i++) {
strMe = strMe.concat(i);
}
var re = new RegExp(targetNumber,"g");
var num1 = strMe.length;
var num2 = strMe.replace(re, "").length;
num2 = num1- num2;
return (num2);
}
There has to be a faster way still...