The idea behind the following code is to test if any number between 0 and 13 + any other number equals 13. If one does both numbers should be saved to a different array but on the same index. So i should have all possible combinations to reach 13 in 2 arrays. But when i run my code I only get 2 combinations which are 0+13 and 13+0. Here is the code:
var number1 = [];
var number2 = [];
var index = 0;
var i = 0;
var j = 0;
//Tests if i + j (from the loop) add up to 13
var test = function(i, j) {
if (i + j === 13) {
number1[index] = i;
number2[index] = j;
index =+ 1;
}
}
//1st loop generates i from 0 to 13 in 0.5 step.
for (i = 0; i < 13.5; i += 0.5) {
//same for j, this number should test with i every loop
for (j = 0; j < 13.5; j += 0.5) {
test(i, j);
}
}
//outputs the 2 arrays, the matching numbers should be stored in
for (i = 0; i < number1.length; i++) {
console.log(number1[i]);
console.log(number2[i]);
}
Change index =+ 1 to index += 1
Then index =+ 1 sets the index to 1 it does not increment it by 1 (as you want)
See Expressions and operators: Assignment operators MDN
Related
I'm a new web developer, been learning web dev for around 8-9 months. I recently became a mentor for new students in the bootcamp I graduated and I wanted to write a simple program to calculate all prime numbers up to a given upper limit. I have solved the exact same problem in C, C++ and Python. I am using the "naive" implementation, not the Sieve of Eratosthenes.
This is the code that works:
"use strict";
function primeNumbers() {
let highNumber;
highNumber = window.prompt("Calculate all prime numbers up to:");
for (let i = 2; i <= highNumber; i++) {
let numberOfDivisors = 0;
for (let j = 2; j < highNumber; j++) {
if (i % j == 0) numberOfDivisors += 1;
}
if (numberOfDivisors == 1) console.log(i);
}
}
Of course, j doesn't have to go all the way up to highNumber, as for any number, all possible divisors are less than half of the number. Thus, I changed the inside for loop making j only going up to Math.round(highNumber / 2 + 1):
"use strict";
function primeNumbers() {
let highNumber;
highNumber = window.prompt("Calculate all prime numbers up to:");
for (let i = 2; i <= highNumber; i++) {
let numberOfDivisors = 0;
for (let j = 2; j < Math.round(highNumber / 2 + 1); j++) {
if (i % j == 0) numberOfDivisors += 1;
}
if (numberOfDivisors == 1) console.log(i);
}
}
But this somehow breaks the code and causes unexpected results. I know all numbers are technically floating point numbers in JavaScript, but I thought that using Math.floor() would help me deal with that.
Any ideas on why this isn't working and what can be done? Thanks!
Try this.
// Utility function to create a range starting from 2
const range = (num: number) => [...Array(num + 1).keys()].slice(2);
const primeNumbers = (limit: number) => {
// Create a range based on the limit
const arr = range(limit);
// Create an array for the prime numbers which will be returned.
// Hardcode 1
const prime: number[] = [1];
// Loop through the range
for (const x of arr) {
// Create an array of divisors by filtering through
// new range based on x
const divisors = range(x).filter((num) => !(x % num));
// If there is only 1 divisor and it === x, it is prime
if (divisors.length === 1 && divisors[0] === x) prime.push(x);
}
return prime;
};
console.log(primeNumbers(50).length);
Here is the compiled TypeScript:
"use strict";
const range = (num) => [...Array(num + 1).keys()].slice(2);
const primeNumbers = (limit) => {
const arr = range(limit);
const prime = [1];
for (const x of arr) {
const divisors = range(x).filter((num) => !(x % num));
if (divisors.length === 1 && divisors[0] === x)
prime.push(x);
}
return prime;
};
console.log(primeNumbers(50).length);
A number always have two divisors, 1 and the number itself. j != i would ensure that an unnecessary computation does not takes place. I have initialized numberOfDivisors as 2 in the declaration. As we iterate, we check if numberOfDivisors increases any further. If so, that is not a prime number.
"use strict";
function primeNumbers() {
let highNumber;
highNumber = window.prompt("Calculate all prime numbers up to:");
for (let i = 2; i <= highNumber; i++) {
let numberOfDivisors = 2;
for (let j = 2; j < Math.round(highNumber / 2 + 1), j != i; j++) {
if (i % j == 0) numberOfDivisors += 1;
}
if (numberOfDivisors == 2) console.log(i);
}
}
I'm learning JavaScript at the moment and have an exercise to solve. The exercise is given bellow:
Output prime numbers
An integer number greater than 1 is called a prime. if it cannot be divided without a
remainder by anything except 1 and itself.
In other words, n > 1 is a prime if it can’t be evenly divided by anything except 1 and n .
For example, 5 is a prime, because it cannot be divided without a remainder by 2 , 3 and 4 .
Write the code which outputs prime numbers in the interval from 2 to n .
For n = 10 the result will be 2,3,5,7 .
P.S. The code should work for any n , not be hard-tuned for any fixed value.
Now i try to solve it this way.
let n = 20;
outer:
for (let i = 2; i < n; i++) {
for (let j = 1; j < n; j++) {
while (j>1 && j<i) {
if (i%j == 0 ) {
continue outer
}
}
}
console.log(i);
}
but it show wrong output
now i also can solve it in this way
let n = 20;
let result = 0;
outer:
for (let i = 2; i < n; i++) {
for (let j = 2; j < i; j++) {
if (i%j == 0) {
continue outer
}
}
console.log(i)
}
Now I ask for your help to know that exactly in where I did mistake in 1st Salutation .
The problem is that if if (i%j == 0 ) is false you remain in the while without changing the variables so you are infinite stuck there.
You could add another label for the inner for and either go to the one or the other
let n = 20;
outer: for (let i = 2; i < n; i++) {
inner: for (let j = 1; j < n; j++) {
while (j>1 && j<i) {
if (i%j == 0 ) {
continue outer;
} else {
continue inner;
}
}
}
console.log(i);
}
I'm trying to make a loop where one value goes up while the second goes down.. I cant figure it out. As far as I can see checkNumber counts down correctly, and x and i are incorrect
I know i'm making a silly mistake somewhere but I'm brand new to coding
var checkNumber = 5;
for (var x = 0; x < 5; x++) {
for (var i = 0; i < checkNumber; i++) {
console.log(checkNumber);
checkNumber = checkNumber - 1;
console.log("x",x,"i",i);
}
}
Just use a single loop and take the difference of the max value and the actual value (minus one, because of the zero based nature) for the second value.
var value = 5,
i;
for (i = 0; i < value; i++) {
console.log(i, value - i - 1);
}
I'm assuming you're trying to do this:
var checkNumber = 5;
for (var x = 0; x < checkNumber; x++) {
for (var i = checkNumber - 1; i >= 0; i--) {
console.log(checkNumber);
console.log("x", x, "i", i);
}
}
This will start i at 4 (minus one to avoid index issues if that's what you're looking for, otherwise remove the -1) and go down to 0.
The first loop will count up until 4.
The trick is to use i-- and set i to something higher, then stop the loop with the second condition in the for.
Does that make sense?
This will make i start at 0 and j start at 4. While i goes up to 4, j will go down to 0.
var checkNumber = 5;
for(var i = 0, j = checkNumber - 1; i < checkNumber; i++, j--){
console.log(i + " " + j);
}
So, I'm new to javascript, and - after completing the JS unit on codecademy, I'm working through Project Euler to get a better feel for the language. The problem is that I'm stuck on the second challenge. I feel pretty dumb at this point. The problem is to find the sum of all the even fibonacci numbers that are less than four million.
var fib = [1,2];
var stack = [];
for (i = 2; i < 4000000; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
That part works. I'm using JSFiddle, and it will print out the fibonacci sequence up to four million. The problem is the next part:
for (j = 0; j < fib.length; j++) {
if (fib[i] % 2 === 0) {
stack[j] = fib[i];
}
}
I've tried that bit both inside and outside the for loop, and I can't figure this out. I have this feeling that I'm missing something obvious. Any help would be appreciated. Thanks :D
EDIT: I figured it out. Thank all of you! Here's what I did:
var total = 0;
var fib = [1, 2];
//In my first attempt, I made a set of the first 4,000,000
//fibonacci numbers. I just left the "4000000" there
//arbitrarily.
for (i = 2; i < 4000000; i++) {
//This makes sure that I don't go over 4000000 in the array.
if (fib[i - 1] < 4000000) {
fib[i] = fib[i - 1] + fib[i - 2];
}
}
for (j = 0; j < fib.length; j++) {
if (fib[j] % 2 === 0) {
total += fib[j];
}
}
alert(total);
And it printed out the correct answer! Woot.
Replace this
for (j = 0; j < fib.length; j++) {
if (fib[i] % 2 === 0) {
stack[j] = fib[i];
}
}
with this
for (j = 0; j < fib.length; j++) {
if (fib[j] % 2 === 0) {
stack[j] = fib[i];
}
}
And also, the problem says to only find fibonacci numbers below 4_000_000. There is no need to create 4 million fibonacci numbers. That would take forever. Try something smaller like 70.
I see a couple of issues with this.
You say that you want to find the sum of all even fibonacci numbers? I don't get the point of putting the even results into another array and then dealing with them. Try something like this:
var fib = [1,2];
var result = 0;
for (i = 2; i < 4000000; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
for (j = 0; j < fib.length; j++) {
if(fib[j] % 2 == 0){
result = result + fib[j];
}
}
Secondly, you phrase it as "all even fibonacci numbers less than 4 million". Are you sure that they want the first 4 million fibonacci numbers, or the fibonacci numbers that are under 4 million?
im trying to obfuscate a string in vb.net and deobfuscate in javascript.
For i = 0 To Len(sData) / 4
For j = 1 To 4
ConvertData2 = ConvertData2 & Mid$(sData, (4 * i) + 5 - j, 1)
Next j
Next i
the above said code works well in vb.net. I need the equivalent code in javascript
i tried the below one but not working.
for (i = 0; i<(sData.length)/4; i++)
{
for (j = 1;j<4;j++)
s=s+sData.substr((4 * i) + 5 - j,1)
}
anyone can suggest where i made mistake..
Well, for one thing, Javascript string indices start at 0, not 1. And your for (j=1; j<4; j++) loop will only count from 1 to 3 anyway; you want to go either from 0 to 3 (j=0 and j<4) or 1 to 4 (j=1 and j<=4).
A direct translation of the VB looks like this:
convertData2 = ''
for (var i=0; i < sData.length / 4; ++i) {
for (var j=1; j <= 4; ++j) {
convertData2 += sData.substr(4 * i + 4 - j, 1)
}
}
the first glaring difference is that in vb.net you use integer division while in javascript you are not...
use
for(var i = 0, len = Math.floor(sData.length / 4); i<=len; i++)
The second is that Mid starts counting from 1 while subst starts from 0
so use
s = s + sData.substr((4 * i) + 5 - j -1,1)
or simplified
s = s + sData.substr((4 * i) + 4 - j,1)
Lastly the loops, when using < do not use the final number ... while the from.. to uses the last number as well (so use <=)
so alltogether
var s = ''; // define s (if not yet defined) other wise use s = '' to make sure it starts empty..
for(var i = 0, len = Math.floor(sData.length / 4); i <= len; i++) {
for (var j = 1 ; j <= 4; j++) {
s = s + sData.substr( (4 * i) + 4 - j,1);
}
}