I want to write javascript code to get a addition countdown - javascript

so basically this the prompt:
Addition countdown
you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)
I'm stuck can someone please help me????!!

You can keep total in one variable outside of while loop.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}

You could change the algorithm a bit, because for the first value, you need no plus sign for the output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));

Related

In javascript how to make multiplication table to be generated by default of 5 or any other number, if the user enters no input number?

Write a program to take input a number from user &
display it’s multiplication table on your browser. If user
does not enter a new number, multiplication table of 5
should be displayed by default.
And this is how I want it to be generated with by default table of 5 encoded,
var num = prompt("Enter Number", "0") //prompt user to enter the number
var num = parseInt(num); //parse the num to number
var i = 0;
document.write('<table border="1" cellspacing="0">');
for (i = 1; i < 10; i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num * i + "</td></tr>");
}
This will help you with your problem. It works like this. if parseInt(num) is a truthy(not 0) it'll use parseInt(num) else if it is falsy(0) then it'll use 5
var num = prompt("Enter Number", "0") //prompt user to enter the number
var num = parseInt(num) || 5;

Cannot get a JavaScript program to add odd numbers

Here's the problem:
Create a sum program that calculates the sum of all odd numbers between 1 and the number entered by the user. For example if the user enters in the number 7 the program would calculate 1 + 3 + 5 + 7. The total and the expression should be displayed on the document. The answer would be 16.
My code so far
//declare the variables
var sternum = prompt("enter a number");
var tantalum = 1;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(sternum % 2 == 0) {
}
else{
document.write(increase + expression);
increase = increase + 1;
tantalum = tantalum + increase;
}
}while(increase < sternum);
document.write(sternum + " = " + tantalum);
You have created an infinite loop. Make sure you increment increase every iteration:
var sternum = prompt("enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(increase % 2 == 0) {
}
else{
document.write(increase + expression);
tantalum = tantalum + increase;
}
increase = increase + 1;
}while(increase <= sternum);
document.write(" = " + tantalum);
To make it more efficient you could change increase = increase + 1; to increase = increase + 2;. No need to process even numbers. Also tantalum should be set to 0 to start.

javascript: summing even members of Fibonacci series

Yet Another (Project Euler) Fibonacci Question: Using (vanilla) javascript, I'm trying to sum the even numbers <= a given limit:
First, something is wrong with my 'if' statement, as some of the results (below) are wrong:
function fibonacciSum(limit) {
var limit = limit;
var series = [1,2];
var sum = 0;
var counter = 0;
for (var i=1; i<=33; i++) { // 33 is arbitrary, because I know this is more than enough
var prev1 = series[series.length-1];
var prev2 = series[series.length-2];
var newVal = prev1+prev2;
series.push(newVal);
counter ++;
console.log("series "+ counter + " is: " + series);
if (series[i] % 2 === 0 && series[i] <= limit) { // intending to sum only even values less than/equal to arbitrary limit
// sum = sum + series[i];
sum += series[i];
}
/*
var sum = series.reduce(function(a,b) {
/*
possible to filter here for even numbers? something like:
if (a %2 === 0)
*/
return a+b;
});
*/
console.log("SUM " + counter + ": " + sum);
} // for loop
} // fibonacci
fibonacciSum(4000000);
Results:
series 1 is: 1,2,3
SUM 1: 2
series 2 is: 1,2,3,5
SUM 2: 2
series 3 is: 1,2,3,5,8
SUM 3: 2 // looking for a '10' here
series 4 is: 1,2,3,5,8,13
SUM 4: 10
series 5 is: 1,2,3,5,8,13,21
SUM 5: 10
series 6 is: 1,2,3,5,8,13,21,34
SUM 6: 10 // looking for '44' here
Can someone please explain why neither of these working as intended?
if (series[i] % 2 === 0) { ...
... or
if (series[i] % 2 === 0 && series[i] <= limit) { ...
And secondly, as you can see I had also tried to use series.reduce(... but I can't figure how to sum only the even values; is that doable/cleaner?
Thank you,
Whiskey T.
No need for arrays. Use three variables for let's say previous, current and next numbers in fibonacci sequence.
We can also begin the sequence with 2 an 3 because there are no other even numbers that will affect the result.
We initialize the sum of even numbers with 2 because it's the current number and it's even. In a do...while we advance with the numbers in sequence and if the new numbers are even we add them to the sum. Stop when limit is reached.
function fibEvenSum(limit) {
var prev = 1,
current = 2,
next;
var sum = 2;
do {
next = prev + current;
prev = current;
current = next;
if (current >= limit)
break;
if (current % 2 == 0)
sum += current;
} while (true)
return sum;
}
This algorithm can be improved using properties of odd and even numbers:
odd + odd = even
even + even = even
even + odd = odd
This should work for you...
var fibonacciSum = function(limit) {
var nMinus2 = 1, nMinus1 = 2, evensFound = [2], sum = nMinus1;
while (sum <= limit){
var n = nMinus1 + nMinus2;
if (n % 2 == 0){
sum += n;
if (sum > limit){
break;
}
evensFound.push(n);
}
nMinus2 = nMinus1;
nMinus1 = n;
}
console.log("Evens found - " + evensFound);
return evensFound;
};
var evensFound1 = fibonacciSum(4),
evensFound2 = fibonacciSum(10),
evensFound3 = fibonacciSum(60),
evensFound4 = fibonacciSum(1000);
$(evenResults).append(evensFound1
+ "<br/>" + evensFound2
+ "<br/>" + evensFound3
+ "<br/>" + evensFound4);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="evenResults"></div>
A solution in the spirit of the one your attempted — with arrays — though as pointed out, they are not necessary.
var i = 0, sequence = [1, 2], total = 0;
while (sequence.slice(-1)[0] < 4000000) {
sequence.push(sequence.slice(-1)[0] + sequence.slice(-2)[0]);
}
for ( i; i <= sequence.length; i++ ) {
if ( sequence[i] % 2 === 0 ) {
total += sequence[i];
}
}

Extra + in output when looping; javascript

My desired output is: 5 + 6 + 7 + 8 + 9 + 10 = 45
The output I'm getting is: 1 + 2 + 3 + 4 + 5 + = 15 (with an extra + side on the end). I'm not sure how to get it to output without the extra + at the end, and am clearly not searching for the right terms to figure it out. Thanks!
Here's my code:
function exercise7Part2() {
// PART 2: YOUR CODE STARTS AFTER THIS LINE
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart + " + ");
loopStart++;
}
document.write(" = " + total);
}
It's because you're printing loopState + "+" which will always print the + at the end. Instead you must check if it's the last value and prevent the + from printing or else, use a ternary operator to print it.
In this example, I'm checking if both loopStart and loopMax are not equal. if they're not equal then am appending + at the end.
It will be like:
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
Here (loopStart!=loopMax ? "+" : "") is a ternary operator. The loopStart!=loopMax is an boolean expression. It's evaluated and if it's true the first parameter after ? will be used so in this case + and if its false anythign after : will be used so in this case its "" empty string.
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);
With normal if condition block
while (loopStart <= loopMax)
{
total += loopStart;
if(loopStart===loopMax) {
document.write(loopStart);
} else {
document.write(loopStart+ "+");
}
loopStart++;
}
// Declare variables
var loopStart;
var loopMax;
var total;
// Assignments
loopStart = Number(prompt("Enter a number:"));
loopMax = Number(prompt("Enter a number larger than the last:"));
total = 0;
// Processing
while (loopStart <= loopMax)
{
total += loopStart;
document.write(loopStart+ (loopStart!=loopMax ? "+" : ""));
loopStart++;
}
document.write(" = " + total);

Take a 4 digit input and change order

I am trying to prompt user for a 4 digit number. Then, replace each
digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then output the encrypted digits.
So, if i enter in 1234 it should encrypt it to 0189 or enter in 5948 and it encrypt it to 1526
The problem is i get 9810 and 6251. So, its reading it backwards. I am close but its in the wrong order.
<script type="text/javascript">
var temp;
var number;
var first;
var second;
var third;
var fourth;
var fifth;
//prompt for first number
do {
inputNumber = window.prompt("Enter only a 4 digit number");
if ((isNaN(inputNumber) || !(inputNumber.length == 4)))
window.alert("please enter a number or length of 4");
} while ((isNaN(inputNumber)) || !(inputNumber.length == 4));
//temp = inputNumber;
temp = parseInt(inputNumber);
first = temp % 10; //process each number one by one
temp = temp / 10;
second = temp % 10;
temp = temp / 10;
third = temp % 10;
temp = temp / 10;
fourth = temp % 10;
swap = first;
first = third;
third = swap;
swap = second;
second = fourth;
fourth = swap;
first = parseInt(first);
second = parseInt(second);
third = parseInt(third);
fifth = parseInt(fifth);
fourth = parseInt(fourth);
first = (first + 7) % 10
second = (second + 7) % 10
third = (third + 7) % 10
fourth = (fourth + 7) % 10
var incrypted = first * 1000 + second * 100 + third * 10 + fourth * 1;
//var incrypted = first * 1000 + second + third * 10 + fourth * 1;
document.writeln("<h1>The number " + inputNumber + " is encrypted as " + incrypted + ".</h1><br />");
</script>
You may be better off handling your numbers individually.
var digits = inputNumber.split("");
digits[0] = (+digits[0]+7)%10;
digits[1] = (+digits[1]+7)%10;
digits[2] = (+digits[2]+7)%10;
digits[3] = (+digits[3]+7)%10;
digits.push(digits.shift());
digits.push(digits.shift());
// rotating by two results in 1234 becoming 3412, same result just more efficient!
var result = digits.join("");
try
var num = "1234"
var digits = num.split("");
var out = [];
for(var i=0; i<digits.length; i++){
digits[i] = (parseInt(digits[i])+7)%10;
}
var end = [digits[2],digits[3],digits[0],digits[1]].join("");
console.log(end.join(""));
A shuffle function:
function shuffle(val){
val = val + "";
function transform(num) { return (+num + 7) % 10 + ""; }
return transform(val[2]) +
transform(val[3]) +
transform(val[0]) +
transform(val[1]);
}
and with some validation:
function shuffle(val){
val = val + "";
if(isNaN(val)) throw "a valid number is required";
if(val.length != 4) throw "a four-digit number is required";
function transform(num) { return (+num + 7) % 10 + ""; }
return transform(val[2]) +
transform(val[3]) +
transform(val[0]) +
transform(val[1]);
}
This comes down to a fundamental misunderstanding of how the % operator works.
The MDN reference states this about the % operator:
The modulo function is the integer remainder of dividing var1 by var2.
For example, 12 % 5 returns 2.
Taking your example, with the input 1234, you are first finding the modulo 10 of 1234 in this code:
first = temp % 10;
The modulo of 1234 is 4 because 1230 is divisible by 10, leaving 4 as the remainder. Thus your logic reversus things. You could just change things at the beginning of your code to be reversed a bit:
fourth = temp % 10; //process each number one by one
temp = temp / 10;.
third = temp % 10;.
temp = temp / 10;
second = temp % 10;
temp = temp / 10;
first = temp % 10;
There is still a problem, when fixed as above you code will output 189 as the answer because you are combing the numbers back together with addition arithmetic rather than string concatenation, as in 0 + 1 + 8 + 9 = 189. Change that last line to look like this and you are fixed:
var incrypted = first + '' + second + '' + third + '' + fourth;
This worked for me;
<script>
var vec = new Array("1","2","3","4");
for(var i = 0; i<4; ++i){
vec[i] = (+vec[i] + 7) % 10;
}
var tmp = vec[1];
vec[1] = vec[3];
vec[3] = tmp;
vec = vec.reverse();
tmp = Number(vec.splice(0,1));
vec.push(tmp);
console.log("vec:", vec);
</script>
logs vec: [0, 1, 8, 9]

Categories

Resources