If number are equal and even pop an alert - javascript

I have few problems with JavaScript. I don't know why it's not working. I've searched the internet but didn't find anything.
I need to popup an alert if both number are equal to popup number (if they are equal) if not, an alert with message (Please insert numbers). But I can't make it work.
function even(){
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
var s = 0 ;
var i;
if (n < m) {
i = n;
while (i <= m){
if(i % 2 === 0)
s += i;
i++;
}
alert(s);
}
else if (n > m) {
i = m;
while (i <= n) {
if (i % 2 === 0)
s += i;
i++;
}
alert(s);
}
else if (n = m) {
i = m;
i = n;
while(i % 2 == 0)
s == i;
}
alert(s);
}
}
<input type="text" id="n" > </br><br>
<input type="text" id="m" > </br><br>
<button type="button" onclick="even()">Sum Even Numbers</button>

function even(){
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
if(n % 2 == 0 && m % 2 == 0){
alert(n + m);
}
}
This is way simpler and does work only if n & m are even numbers. Thanks to n % 2 == 0 and m % 2 == 0 which divide the numbers by to and check if the remainder is equal to 0.
EDIT
But reading your question again I'm not sure it is you want to achieve. You might want to be more precise.

Based on the code you have above, I assume goal is to sum the even numbers between n and m. Something like this? Perhaps,
function even() {
var n = parseInt(document.getElementById("n").value);
var m = parseInt(document.getElementById("m").value);
var s = 0;
var start = Math.min(n, m);
var end = Math.max(n, m);
for (var i = start; i <= end; ++i) {
if (i % 2 === 0) {
s += i;
}
}
alert(s);
}
jsFiddle
Notes
while(i%2 == 0) s == i; should probably be while(i % 2 == 0) { s = i; }
}else if(n=m) { should probably be } else if (n === m) {
I used Math.min() and Math.max() since it seemed like the first two sections of your if-statement did the same thing but with n and m swapped.

Related

JavaScript: Somehow my var n from input gets multiplied by 10 I have no idea where it happens

I have been doing a fibo function for practicing and suddenly I get the n number acquired form the input field always multiplied by 10. So if I type 1 will calculate 11 numbers from fibo sequence if I type 2 will do 21 numbers and so on.. Does someone spot where is the mistake?
function fibo(){
var n = document.getElementById("numb").value;
console.log(n);
var r=[];
var i;
if (isNaN(n) || n < 1 || n > 10) {
document.getElementById("ex1").innerHTML = "Input not valid";
} else {
for (i = 0; i < n + 1; i++) {
console.log(i);
console.log(r);
if (i == 0){
r[i] = i;
}
else if (i == 1){
r[i] = i;
}
else{
r[i] = r[i - 1] + r[i - 2];
}
}
document.getElementById("ex1").innerHTML = r.toString();
}
}
<!DOCTYPE html>
<html>
<body>
<h2>Fibonacci</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="fibo()">Calculate Fibo</button>
<p id="ex1"></p>
</body>
</html>
I just had to remove the "+1" in the for loop. Thanks anyway.
function fibo(){
var n = document.getElementById("numb").value;
var r=[];
var i;
if (isNaN(n) || n < 1 || n > 10) {
document.getElementById("ex1").innerHTML = "Input not valid";
} else {
for (i = 0; i < n ; i++) {
if (i == 0){
r[i] = i;
}
else if (i == 1){
r[i] = i;
}
else{
r[i] = r[i - 1] + r[i - 2];
}
}
document.getElementById("ex1").innerHTML = r.toString();
}
}
<!DOCTYPE html>
<html>
<body>
<h2>Fibonacci</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="fibo()">Calculate Fibo</button>
<p id="ex1"></p>
<script src="fibo.js"></script>
</body>
</html>

javascript - functions and equations confusion

var number = prompt('Input a number!');
var n = number;
function getList() {
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0)
console.log (n);
}
}
console.log(getList());
console.log((n*(n+1))/2);
//equation for summation: (n*(n+1))/2
I'm trying to return the sum of numbers divisible by 3 or 5 up to 17. So far, it half-works; it lists all the numbers, but I can't find a way to return the sum.
I have the equation for summation, but I can't find a way to put it in so that it works. How do you get the equation to reference the list instead of referencing the inputted number?
The answer is supposed to be 60. Any clue? Thanks!
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 === 0 || n % 5 === 0)
sum += n;
}
console.log(sum);
Use a variable to add the numbers and return it after for loop.
Below it the exapmle.
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
sum += n;
}
}
return sum;
}
console.log(getList());
Two things:
Just return the sum from your getList function
Make sure your prompt input is converted to integer otherwise it will be treated as a string and your n*(n+1)/2 will be wrong
var number = parseInt(prompt('Input a number!'));
var n = number;
function getList() {
var sum = 0;
for (var n = 1; n <= 17; n++) {
if (n % 3 == 0 || n % 5 == 0) {
console.log (n);
sum += n;
}
}
return sum;
}
console.log(getList());
console.log(n, (n*(n+1))/2);
If you want an equation :)
function sumOfNumbersDivisibleBy3Or5(n) {
const by3 = Math.floor(n/3),
by5 = Math.floor(n/5),
by3And5 = Math.floor(n/3/5);
return 3*by3*(by3+1)/2 + 5*by5*(by5 + 1)/2 - 3*5*by3And5*(by3And5 + 1)/2
}
console.log(sumOfNumbersDivisibleBy3Or5(17))
var number = prompt('Input a number!');
function getList() {
var sum = 0;
for (var n = 1; n <= number; n++) {
if (n % 3 == 0 || n % 5 == 0)
sum+=n;
}
return sum;
}
console.log(getList());
it will return sum of all the number which is divisible by 3 or 5 in between 1 and entered number

How does (else) if and || work and which is better?

I don't know how these 2 block of codes executes,they have different outputs, do I have to use else if on the first block, if so, which is faster?
demo
var output = 0;
for (var n = 0; n < 100; n++) {
if (n % 3 === 0) {
output += n;
}
if (n % 5 === 0) {
output += n;
}
}
console.log(output);
/* ------------------------- */
var sum = 0;
for (var x = 0; x < 100; x++) {
if (x % 3 === 0 || x % 5 === 0) {
sum += x;
}
}
console.log(sum);
If you use else if instead of the second if in the first block, you should get the same results.
For example, n=15:
in the first block of code:
you check n%3 === 0 is true, so output is increased by 15
you check n%5 === 0 is true, so output is increased by 15 again
in the second block of code:
you check n%3 === 0 is true, no other checks are done, sum is increased by 15
if you use else if:
you check n%3 === 0 is true, so output is increased by 15
no other checks are done
I believe || and else if speeds are pretty the same. Hope it helps
In the first block of code, for the numbers divisible by 15(lowest common multiple of 3 and 5), sum was getting added twice.
In the second block of code, as its a || statement. Only once sum was added if its a multiple of 15.
Check the third block of code, I added. I am just looking for the sum of the multiples of 15. See its the exact diff you were finding.
var output = 0;
for (var n = 0; n < 100; n++) {
if (n % 3 === 0) {
output += n;
}
if (n % 5 === 0) {
output += n;
}
}
console.log(output);
/* ------------------------- */
var sum = 0;
for (var x = 0; x < 100; x++) {
if (x % 3 === 0 || x % 5 === 0) {
sum += x;
}
}
console.log(sum);
/* ------------------------- */
sum = 0;
for (x = 0; x < 100; x++) {
if (x % 15 === 0) {
sum += x;
}
}
console.log(sum);

How do you make every 9th element in Math.random array to be the same element?[javascript]

I have this bit of code here
<script language='javascript' type='text/javascript'>
var imagesArray = ["1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png","9.png","10.png","11.png","12.png","13.png","14.png","15.png","16.png","17.png","18.png","19.png","20.png","21.png" ];
var newArray = new Array(100);
for (i = 0; i < 100; i++)
{
if (i % 9 === 0)
{
}
else
{
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
}
}
</script>
the idea behind is that i need it so that every 9th number that would be randomly chosen would remain the same, but i have no idea what do i put there so it would work.
Do you got any advice?
Thanks!
Here is a sample of what you can do :
First fill your array with Math.random() or whatever you want.
imagesArray[i] = Math.floor((Math.random() * 10) + 1);
If you want the value to be the same every 9 elements , use a loop starting at 9 and going through every 9 elements with i+9
for(var i = 9; i < yourArray.length ; i = i + 9){
imagesArray[i] = imagesArray[9];
}
Actually you can start the loop at 18 as well
Demo
Try defining a variable outside of for loop to store value at first i % 9 === 0
var newArray = new Array(100), ninth = null;
for (i = 0; i < 100; i++) {
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
if (i % 9 === 0 && ninth === null && i === 9) {
ninth = newArray[i]
};
if (i % 9 === 0 && i >= 9) {
newArray[i] = ninth;
};
}

How to avoid this bad for loop?

I'm trying to loop through a big number (6 billion to be exact), but I can't because my computer freezes. How can I work my way around this. I'm supposed to find the largest prime factor of 600851475143.
function prime(n) {
if (n === 1 || n === 2) return false;
if (n % 2 === 0 || n % 3 === 0) return false;
return true;
}
var n = 600851475143;
for (var i = 1, c = []; i < n; i++) {
if ((n % i === 0) && prime(i)) {
c.push(i);
}
}
I'm done with it yet. I'm storing the primes in an array.
Your prime() function doesn't do what the name says it should. There are many efficient ways of factoring primes, try this one for example:
var x = 600851475143;
var i = 2;
var sk;
while(i <= x)
{
while (x % i == 0)
{
sk = i;
x = x / i;
}
i++;
}
console.log(sk);
Output: 6857
This page has another (view source) function for factoring.
That prime function doesn't returns prime numbers only, but all those positive integers that aren't 1 or divisible by 2 and 3.
Let's see the whole algorhythm again. First of all, notice that you don't need to iterate through n, you can stop at its square root (think about it).
var divs = [];
if (!(n & 1)) { // Checking if n is even, using faster bit operators
divs.push(2);
while (!(n & 1)) n >>= 1;
}
var d = 3, l = Math.sqrt(n);
while (d < l) {
if (!(n % d)) {
divs.push(d);
while (!(n % d)) n /= d;
l = Math.sqrt(n);
}
d += 2; // No even numbers except 2 are prime, so we skip them
}
if (n !== 1) divs.push(n);
Now divs[divs.length - 1] contains your largest prime divisor of n, and divs all the prime factors.

Categories

Resources