JavaScript - Project Euler #5 -- efficiency - javascript

This is for Project Euler, problem #5.
The task is to find the smallest number evenly divisible by numbers 1-20. My code seems to work on 1-18, but at 19 my browser starts timing out. This leads me to believe my code is just inefficient.
How can I mitigate this?
function divisible(a){
counter = 0;
result = 2;
while (counter < a){
for (var x = 0; x <= a; x ++){
if (result % x === 0){
counter ++;
}
}
if (counter != a){
counter = 0;
result ++;
}
}
return result;
}
divisible(20)

Basically, you want the least common multiple of 1,...,20.
I would implement lcm by using gcd, which can be implemented using the fast Euclidean algorithm.
function gcd(a, b) {
return b === 0 ? a : gcd(b, a%b); // Euclidean algorithm
}
function lcm(a, b) {
return a * b / gcd(a, b);
}
function divisible(a){
var result = 1;
for(var i=2; i<=a; ++i)
result = lcm(result, i);
return result;
}
divisible(20); // 232792560

Yup, inefficient. You would need to change the algorithm. The most efficient I can think of is to factorise all the numbers from 2 to 20 (with factors and counts: e.g. 18 is 3 * 3 * 2, or twice 3 and once 2, for final { 3: 2, 2: 1 }); then find the maximum for each factor, and multiply them together.
An abbreviated example: the least number that is divisible by 18 and 16:
18: { 3: 2, 2: 1 }
16: { 2: 4 }
maximums of factor repetitions: { 3: 2, 2: 4 }
result: 3^2 * 2^4 = 144
Factorising numbers from 2 to 20 is easy; if you don't know how to do it, there are many possible algorithms, you can see the Wikipedia article on integer factorisation for ideas.

another option with brute force and modulo rest-classification
this problem can be solved with a simple common modulo rest class characteristics.
look at the numbers from 1 to 20 and divide it into two groups and find some unique common attributes between them.
1 2 3 4 5 6 7 8 9 10
we are building a division with the same reminder members
1 divides all
2 divide 4,8 -->>8 important
3 divide 6,9 but 6 doesnt divide 9 evenly--> 6,9
5 divide 10-->> 10 important
that leaves us with 6,7,8,9,10 to check if there is any number from 1 that can divide this with rest 0.
the trick is if 2,4,8 divides a number let say 16 with the same reminder then we don't have to check if 2,4 divides 16, we check only 8.
11 12 13 14 15 16 17 18 19 20
here we can do the same from about with factors of the numbers from above and we will be left with
11 12 13 14 15 16 17 18 19 20
NB: we know that the last number that has to divide the number is 20,
so that means either the solution will be a number ending with 0 or is
one of the factors of 20, so we build factors of 20 and check if 11 12
13 14 15 16 17 18 19 can divide it then we are done.
int start = 20;
while (start % 11 != 0 || start % 12 != 0 | start % 13 != 0 || start % 14 != 0 ||
start % 15 != 0 || start % 16 != 0 || start % 17 != 0 || start % 18 != 0 || start % 19 != 0 )
{
start += 20;
}
console.log(start)
The same idea applies analogue to the first deduction I made to make the
problem seems smaller.
//smallest number divisible by all numbers from 1 to 10
int a = 10;
while (a % 6 != 0 || a % 7 != 0 | a % 8 != 0 || a % 9 != 0 )
{
a += 10;
}
console.log(a)
//smallest number divisible by all numbers from 1 to 5
int i = 5;
while (i % 3 != 0 || i % 4 != 0)
{
i += 5;
}
console.log(i)

Related

I want to filter only odd negative numbers from an array. Why does n % 2 === 1 not work, but n % 2 !== 0 does?

Write a function that returns only negative odd numbers from an array.
const arr = [4, -7, -6]
I first tried:
let negativeOdd = arr.filter(n => n % 2 === 1 && n < 0);
return negativeOdd;
result was an empty array. []. The answer should be [-5].
But when I replaced n % 2 === 1 with n % 2 !== 0, it workded. I am new to JS and was hopeing somenone could help me understand why this is happening. Thank you.
The modulo % operator in Javascript divides a number by a divisor (in this case 2), and returns the remainder.
-5 divided by 2 is -2.5, or -2 with a remainder of -1. 2 * -2 + -1 = -5
5 divided by 2 is 2.5, or 2 with a remainder of 1. 2 * 2 + 1 = 5
console.log(-5 % 2);
console.log(5 % 2);
A negative odd number gives
n % 2 === -1.
Just try it out. In the console, type
-5 % 2
There are different possible definitions of the modulus with respect to negative numbers. For some implementations, it's always true that 0 <= |a % b| < |b|; this is tantamount to always using the floor() function to find the integer quotient before computing the remainder. There are many languages with this interpretation, including Common Lisp and Python. You can get a negative value out of the % operator in these languages, but only if the divisor is negative; the sign of the dividend doesn't change the sign of the result.
In other languages, -|b| < |a % b| < |b|, and the sign of the result does depend on the sign of the dividend. This is equivalent to obtaining the integer quotient by rounding toward zero before taking the remainder; C is in this category (since C99; previous editions of the spec left it up to the implementation). So is Javascript, which is why -1 % 2 is not 1, but -1.
The first definition is often more useful, but easy to define in terms of the second:
const mod = (a,b) => (a % b + b) % b // mod(-1,2) is 1

in Primality Test ,i do not understand why we increase i by 6 (i=i+6) ? and the if statment conditions in the for loop block?

i need some help please !!
this is the code i founded in data-strucure book i understand that t all primes are of the form 6k ± 1, with the exception of 2 and 3 where k is some integer. the problem is in the for loop why we add 6 to i (i+6) and this condition in if statment if (n%i == 0 || n%(i+2) == 0):
function isPrime(n){
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0) return false;
for (var i=5; i*i<=n; i=i+6){
if (n%i == 0 || n%(i+2) == 0)
return false;
}
return true;
}
firstly, it is checking for 0(mod2) and 0(mod3), we know any one of consecutive 2 numbers are divisible by 2 and any one of 3 consecutive number are divisible by 3 and other must be divisible by 2
so, the for loop starts only if number is not divisible by 2 or 3 and it is >=25. And skip count has simple math behind it.
All integers can be represented as 6k+m, where m ε {0, 1, 2, 3, 4, 5}, and k is some integer. In fact the base of this comes from the fact that all integers can be represented in form of 3k,3k+1,3k+2.
This is obvious. Therefore:
m=0: 6k is divisible by 6. Not prime
m=1: 6k+1 has no immediate factors. May be prime.
m=2: 6k+2 = 2 x (3k+1). Not prime
m=3: 6k+3 = 3 x (2k+1). Not prime
m=4: 6k+4 = 2 x (3k+2). Not prime
m=5: 6k+5 has no immediate factors. May be prime
But 6k+5=6k-1 (mod 6), so only two prime possible are 6k+1 and 6k-1.
The algo says a prime number can be of the form 6k+1 or 6k-1.
Let us assume k is 1 here, then the prime is 5 and 7. So in the first iteration of the loop, this condition does exactly that:
if (n%i == 0 || n%(i+2) == 0)
n%5 or n%7.
Now next i is 11. So the condition becomes,
n/11==0 or n/13==0. Both 11 and 13 are of the form 6k-1 and 6k+1 respectively.
That is why you need an increment of 6 everytime and those two conditions.
thanks for clarify that point by #SebastianSimon "only multiples of 6 need to be checked (twice: once for 6k − 1, once for 6k + 1)" this is the code after refactor it to be more readable with explain every step.
function isPrime(n){
//one is not primary number
if (n <= 1) return false;
//3 and 2 is a primary number
if (n <= 3) return true;
//Any number that is divisible by 2 and 3
//other than the number 2 and 3 is not prime
if (n%2 == 0 || n%3 == 0) return false;
// all primes are of the form 6k ± 1, with the exception of 2 and 3
// where k is some integer,
//so only multiples of 6 need to be checked
//(twice: once for 6k − 1, once for 6k + 1)
//that is the reason why we increase i by 6 (i=i+6) in the for loop.
// the loop only has to test until the square root of n so (i*i<=n)
// This is because if the square root of n is not a prime number,
// n is not a
// prime number by mathematical definition.
for (var i=6; i*i<=n; i=i+6){
//Divisibility test by 6k+1 and 6k-1
if (n%(i+1) == 0 || n%(i-1) == 0)
return false;
}
return true;
}

Last digit of the power of 2 numbers without performing the operation in javascript [duplicate]

This question already has answers here:
How to find the units digit of a certain power in a simplest way
(10 answers)
Closed 3 years ago.
I would like to know how to find the units digit of a number raised to another number without calculating the result of the operation, i.e 5**7 = 78125, so I want to write a function that returns 5 as the last digit of the operation.
This link offer a simple algorithm that explains how to deal with such problem.
Identify the units digit in the base ‘x’ and call it say ‘l’. {For
example, If x = 24, then the units digit in 24 is 4. Hence l = 4.}
Divide the exponent ‘y’ by 4. If the exponent y is exactly divisible
by 4. i.e, y leaves a remainder 0 when divided by 4. Then, the units
digit of pow(x,y) is 6, if l = 2,4,6,8. the units digit of pow(x,y) is 1,
if l =3,7,9. If y leaves a non-zero remainder r, when divided by 4
(i.e y = 4k + r). Then, the units digit of pow(x,y) = pow(I,r) .
A basic implementation of this algorithm :
function getLastDigit(x, y) {
const I = x % 10;
const r = y % 4;
if (r === 0) {
if (I === 2 || I === 4 || I === 6 || I === 8) {
return 6 % 10;
}
if (I === 3 || I === 7 || I === 9) {
return 1 % 10;
}
}
return I ** r % 10;
}
console.log(getLastDigit(2019, 2020));

JS - Unity - Multiples of a Number from a Number

I have a yield WaitForSeconds, transform.position.y=transform.position.y+1; cycle which constantly adds numbers.
At the bottom I will have 52 of these:
function Update () {
if (transform.position.y ? == 1) {
print ("Part2")
}
if (transform.position.y ? == 2) {
print ("Part3")
}
if (transform.position.y ? == 3) {
print ("Part4")
}
etc...
How do I set it so that to get it to say 'Part2', the transform.position.y has to be either 2, 54, 106, etc.. (onwards forever).
Much would be appreciated
Something like this?
if ( transform.position.y == 2 || transform.position.y == 54 || transform.position.y == 106 ) {
print ("Part2");
}
You can just use the mod operator (% in Javascript) which returns the division remainder of two integers.
For example:
7 % 2 = 1
So transform.position.y % 52 will do exactly what you want:
0 % 52 = 0
1 % 52 = 1
2 % 52 = 2
...
51 & 52 = 51
52 % 52 = 0
53 % 52 = 1
54 % 52 = 2
and so on...
To have it go from 1-52 instead of 0-51, you can just add one to the result.
All together:
function Update() {
var part : int = transform.position.y % 52 + 1;
print( "Part" + part.ToString() );
}

Understanding the modulus operator

I have some code that loops through a collection of list elements and a collection of colours. It makes sure each list element is designated to a colour.
I understand everything about this apart from the modulus operator. I get that it finds and uses the remaining number, but I cannot for the life of me understand what it is doing here?
var li = document.getElementsByTagName('li');
var colors = ["salmon", "teal", "orange", "grey", "blue"];
var colorsCount = colors.length;
for ( var i = 0; i < li.length; i++ ) {
li[i].style.backgroundColor = colors[ i % colorsCount ]; // why does this work?
}
Since there is (potentially) a larger number of items in the li array, this prevents i from being outside the bounds of the colors array, since i % colorsCount can never be over colorsCount.
For example, if we had 10 elements in li, and 5 colors, i % colorsCount would be:
i i % colorsCount Color
-------------------------------
0 0 salmon
1 1 teal
2 2 orange
3 3 grey
4 4 blue
5 0 salmon
6 1 teal
7 2 orange
8 3 grey
9 4 blue
More Information on Modulo Operations.
i % colorsCount will set the bound of the index to be between 0 and colorsCount-1, thus ensuring you never index past the end of the array.
Since mod is the remainder, the remainder can never be greater than the divisor (which in this case, is the length of the array).
Perhaps this snippet may help you understand:
var s = ''
for (var i = 0; i < 20; i ++) {
s += (i % 5) + ', '
}
console.log(s)
The result is:
0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4,
Note how the number resets to 0 every time it reaches 5. The % colors.length just makes sure the index never goes above the array's length.
A more descriptive way of understanding:
0 % 5: 0/5 = 0, remainder 0
1 % 5: 1/5 = 1/5, remainder 1
...
5 % 5: 5/5 = 1, remainder 0
6 % 5: 6/5 = 1 1/5, remainder 1
7 % 5: 7/5 = 1 2/5, remainder 2
...
It's cycling your colours. Because you only have a limited number of colours, and any number of possible list items, it makes sure that i will not overflow the bounds of your colors array.
The modulus operator returns the remainder of division. It allows you to loop through and reuse the colors array even though there are potentially less colors in the array than there are elements in your list to color.
If length is say 8,
5 % 1 == (5 / 1) = 0 remainder 1
5 % 2 == (5 / 2) = 0 remainder 2
5 % 3 == (5 / 3) = 0 remainder 3
5 % 4 == (5 / 4) = 0 remainder 4
5 % 5 == (5 / 5) = 1 remainder 0
5 % 6 == (5 / 6) = 1 remainder 1
5 % 8 == (5 / 7) = 1 remainder 2
5 % 7 == (5 / 8) = 1 remainder 3
As you can see, the remainders are what's returned by the mod operator, and they're always less than the length of the colors array.
why does i % colorsCount work?
What it does
This code cycles through colors. It does so using the modulus operator to ensure you're always within the bounds of the array.
How it does it
Modulus operation finds the remainder of division of one number by another.
In your case by taking i modulus the colorsCount:
0 % 5; // 0
1 % 5; // 1
1 % 5; // 2
3 % 5; // 3
4 % 5; // 4
5 % 5; // 0
8 % 5; // 3
The result of a modulus operation is the remainder after division of the left operand by the right operand.
So the line of code in question will always return some number between 0 and colorsCount-1.
You iterate from 0 until how many li elements you have. For this example, say 10.
You then look at the colors array and find the element for that iteration (i) and modulus by how many items are in the colors array.
In short, this is what's happening:
var colorsCount = 10;
1 % 10 = 1 // ... Access colors[1]; (teal)
2 % 10 = 2 // .... Access colors[2]; (orange)
3 % 10 = 3 // .... Access colors[3]; (grey)
4 % 10 = 4 // .... Access colors[4]; (blue)
5 % 10 = 5 // .... Access colors[5];
etc
If you are wondering why it will never access an element outside of the array, the answer is because as i becomes greater, the result becomes smaller.
For example, take iteration 8:
8 % 5 = 3
(Iteration 8, 5 elements in the array)
Therefore you are accessing colors[3];

Categories