Can anyone help me with Counter game solution? - javascript

When I try to run the input, it says that the time limit exceeded. Can anyone help me to reduce this code, thank you.
const counterGame = (n) => {
let count = 0;
for (let i = n; i > 0; i--) {
if (Math.pow(2, i) % 1 === 0 && Math.pow(2, i) === n) {
n /= 2;
count++;
if (n === 1) break;
} else if (Math.pow(2, i) <= n) {
n -= Math.pow(2, I);
count++;
if (n === 1) break;
}
}
if (count % 2 === 0) {
return 'Richard';
} else {
return 'Louise';
}
};

You don't have to iterate over the values to find if n is power of 2. You can use Math.log2() method. Like this,
function counterGame(n) {
let move = 0;
while(n > 1) {
let power = parseInt(Math.log2(n));
let max = 2**power;
if(n === max) {
n = parseInt(n/2);
} else {
n = n - max;
}
move++;
}
if(move %2 === 0) {
return 'Richard';
} else {
return 'Louise';
}
}
console.log(counterGame(6));
console.log(counterGame(8));

You don't need to loop for just checking whether n is power of 2. Check whether this helps or not.
const counterGame = (n) => {
if (n % 2 === 0) {
return 'Richard';
} else {
return 'Louise';
}
};

Related

Sum All Primes Below a Given Number | Intermediate Javascript Algorithm | Recursion

Question
A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.
Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.
My Attempt
const isPrime = a => {
for(let i = 2; i < a; i++)
if(num % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
sumPrimes(10);
The Problem
It says: 'Num is not defined'
I am not sure if there are other errors.
My Question
Please could you help me find the error, and fix the code to solve the algorithm?
This was a simple syntax error identified by #Jonas Wilms (upvote him in the comment above :))!
By replacing the 'a' with 'num' the function was fixed.
const isPrime = a => {
for(let i = 2; i < a; i++)
if(a % i === 0) return false;
return a > 1;
}
function sumPrimes(num, total = []) {
let numVar = num;
let n = total.reduce((aggregate, item)=>{
return aggregate + item;
}, 0);
if(n > numVar){
return n;
}
for(let i = 1; i <= numVar; i++){
if(isPrime(i)== true){
total.push(i);
}
}
return sumPrimes(num, total);
}
console.log(sumPrimes(10));
this simple function may help you,
function isPrime(num) {
for (var i = 2; i < num; i++)
if (num % i === 0) return false;
return num > 1;
}
function sumPrimes(num) {
let tot = 0;
for (let i = 0; i < num; i++)
if (isPrime(i))
tot += i;
return tot;
}
console.log(sumPrimes(10));

Find and print the biggest prime number (JS)

I'm studying node.js and have some interesting task - Write a program that finds and prints the biggest prime number which is <= N.
Input // Output - 13 // 13
126 // 113
26 // 23
In last course with java i have the same task and my code is really simple:
import java.util.Scanner;
public class BiggestPrimeNumber {
public static void main(String[] args){
int n;
Scanner in = new Scanner(System.in);
n=in.nextInt();
while(prim(n) == false){
n--;
}
System.out.println(n);
}
public static boolean prim(int m){
int n=m;
for(int i=2;i<n;i++){
if(n%i == 0){
return false;
}
}
return true;
}
}
I try similar way to test it, but I'm don't have idea how to convert it:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
Can you help me, because I'm really have problem with js using in console.
I think this is what you want. You only need to declare a function and use it as you are doing.
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
If your running it with NodeJS in console, you can save it in a file called prime.js (for example) and execute it with: node prime.js.
You can pass parameters to the script like: node prime.js 126 and then get them in the code. That will be something like that:
const args = process.argv;
let n = args[2];
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(m) {
let n = m;
for (let i = 2; i < n; i += 1) {
if (n % i === 0) {
return false;
}
}
return true;
}
You're pretty close. First off, you don't have isPrime defined. Second, if you were to paste all of your code into the browser console, it isn't going to like that you are defining n twice. I also cleaned up your isPrime bit of code.
let n = 100;
let result = n;
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}
while (isPrime(result) === false) {
result -= 1;
}
console.log(result + " is the next prime below " + n);
Also, remember that javascript is not a compiled language, so unless you are defining your function in a class, the browser will interpret the code sequentially. Therefore, you have to have isPrime defined before you use it.
The algorithm to find the nearest prime number can be further optimized. All prime numbers are of the form 6k+1 or 6k-1 except the numbers 2 and 3. Also, instead of checking all the way to the number the check can be made till Sqrt(n). Here is the modified isPrime function:
let n = 126;
while (isPrime(n) === false) {
n -= 1;
}
console.log(n);
function isPrime(num) {
if (num <= 1) return false;
if (num < 4) return true;
if (num%2 === 0 || num%3 === 0) return false;
for (var i = 5; i*i <= num; i+=6) {
if (num % i === 0 || num % (i + 2) === 0)
return false;
}
return true;
}

How to make Web Worker async?

The task is: work with large amount of data in the Worker and render the result of the algorithm after each iteration (I render dataObj to the HTML). Using following code make web page freezed and slow. How to avoid it?
onmessage = (e) => {
let number = 0;
let totalNumbers = 0;
let primeNumbers = 0;
if (e.data === "start"){
while(true){
totalNumbers++;
if (isPrime(number)){
primeNumbers++;
}
number++;
let dataObj = {
totalNumbers: totalNumbers,
primeNumbers: primeNumbers
}
postMessage(dataObj);
}
} else{
}
}
function isPrime(n) {
if (n == 2 || n == 3 || n == 5 || n == 7) {
return true;
} else if ((n < 2) || (n % 2 == 0)) {
return false;
} else {
for (var i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0)
return false;
}
return true;
}
}

Bug while trying to find sum of primes with javascript

I am trying to get the sum of an array of prime numbers, and I understand there are more elegant ways to do that and have seen the links to those solutions.
My problem is something that's wrong within this specific script, and I'm trying to understand what's causing THIS code to fail.
The issue is that the numbers 9, 15 and many others are being being added into the primes array, even though they all, correctly, fail a test to check if they're prime numbers. I can't wrap my head around what in the script is causing the numbers to push to the array despite failing that test. Again, I'm not looking for a completely different/better approach to summing the primes, but some help in identifying what exactly is wrong in this script would be really appreciated.
function totalPrime(num) {
var nums = [];
var primes = [];
for (var i = 1;
(num - i) > 1; i++) {
nums.push(num - i);
}
nums.forEach(isPrime);
function isPrime(n) {
var a = [];
var test;
if (n === 1) {} else if (n === 2) {
primes.push(n);
} else {
for (var i = 1;
(n - i) > 1; i++) {
a.push(n - i);
}
a.forEach(function(x) {
if ((n % x) === 0) {
test = false;
} else {
test = true;
}
});
if (test) {
primes.push(n);
} else {}
};
}
console.log(primes.reduce(function(a, b) {
return a + b
}));
}
totalPrime(5);
Same script with logging I was using to debug:
function totalPrime(num) {
var nums = [];
var primes = [];
for (var i = 1;
(num - i) > 1; i++) {
nums.push(num - i);
}
nums.forEach(isPrime);
function isPrime(n) {
var a = [];
var test;
if (n === 1) {
console.log(n + ' is NOT a prime number');
} else if (n === 2) {
console.log(n + ' IS a prime number');
primes.push(n);
} else {
for (var i = 1;
(n - i) > 1; i++) {
a.push(n - i);
}
a.forEach(function(x) {
if ((n % x) === 0) {
test = false;
console.log(n + ' % ' + x + ' equals 0');
console.log(x + ' fails check');
} else {
test = true;
console.log(n + ' % ' + x + ' does NOT equal 0');
console.log(x + ' passes check');
}
});
if (test) {
console.log(n + ' IS a prime number.');
primes.push(n);
} else {
console.log(n + ' is NOT a prime number.');
}
};
}
console.log(primes);
console.log(primes.reduce(function(a, b) {
return a + b
}));
}
totalPrime(5);
Your test value in each test override the previous check. Thus, actualy only the last check (divide in 2) become relevant, and all the odd primes fail.
You can correct it by change the default of test to true, and remove the exist line in the code test = true;.
The corrected code:
function isPrime(n) {
var a = [];
var test = true;
if (n === 1) {} else if (n === 2) {
primes.push(n);
} else {
for (var i = 1;
(n - i) > 1; i++) {
a.push(n - i);
}
a.forEach(function(x) {
if ((n % x) === 0) {
test = false;
}
});
if (test) {
primes.push(n);
}
};
}

How to find nth Fibonacci number using Javascript with O(n) complexity

Trying really hard to figure out how to solve this problem. The problem being finding nth number of Fibonacci with O(n) complexity using javascript.
I found a lot of great articles how to solve this using C++ or Python, but every time I try to implement the same logic I end up in a Maximum call stack size exceeded.
Example code in Python
MAX = 1000
# Create an array for memoization
f = [0] * MAX
# Returns n'th fuibonacci number using table f[]
def fib(n) :
# Base cases
if (n == 0) :
return 0
if (n == 1 or n == 2) :
f[n] = 1
return (f[n])
# If fib(n) is already computed
if (f[n]) :
return f[n]
if( n & 1) :
k = (n + 1) // 2
else :
k = n // 2
# Applyting above formula [Note value n&1 is 1
# if n is odd, else 0.
if((n & 1) ) :
f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1))
else :
f[n] = (2*fib(k-1) + fib(k))*fib(k)
return f[n]
// # Driver code
// n = 9
// print(fib(n))
Then trying to port this to Javascript
const MAX = 1000;
let f = Array(MAX).fill(0);
let k;
const fib = (n) => {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
f[n] = 1;
return f[n]
}
if (f[n]) {
return f[n]
}
if (n & 1) {
k = Math.floor(((n + 1) / 2))
} else {
k = Math.floor(n / 2)
}
if ((n & 1)) {
f[n] = (fib(k) * fib(k) + fib(k-1) * fib(k-1))
} else {
f[n] = (2*fib(k-1) + fib(k))*fib(k)
}
return f[n]
}
console.log(fib(9))
That obviously doesn't work. In Javascript this ends up in an infinite loops. So how would you solve this using Javascript?
Thanks in advance
you can iterate from bottom to top (like tail recursion):
var fib_tail = function(n){
if(n == 0)
return 0;
if(n == 1 || n == 2)
return 1;
var prev_1 = 1, prev_2 = 1, current;
// O(n)
for(var i = 3; i <= n; i++)
{
current = prev_1 + prev_2;
prev_1 = prev_2;
prev_2 = current;
}
return current;
}
console.log(fib_tail(1000))
The problem is related to scope of the k variable. It must be inside of the function:
const fib = (n) => {
let k;
You can find far more good implementations here list
DEMO
fibonacci number in O(n) time and O(1) space complexity:
function fib(n) {
let prev = 0, next =1;
if(n < 0)
throw 'not a valid value';
if(n === prev || n === next)
return n;
while(n >= 2) {
[prev, next] = [next, prev+next];
n--;
}
return next;
}
Just use two variables and a loop that counts down the number provided.
function fib(n){
let [a, b] = [0, 1];
while (--n > 0) {
[a, b] = [b, a+b];
}
return b;
}
console.log(fib(10));
Here's a simpler way to go about it, using either iterative or recursive methods:
function FibSmartRecursive(n, a = 0, b = 1) {
return n > 1 ? FibSmartRecursive(n-1, b, a+b) : a;
}
function FibIterative(n) {
if (n < 2)
return n;
var a = 0, b = 1, c = 1;
while (--n > 1) {
a = b;
b = c;
c = a + b;
}
return c;
}
function FibMemoization(n, seenIt = {}) {//could use [] as well here
if (n < 2)
return n;
if (seenIt[n])
return seenIt[n];
return seenIt[n] = FibMemoization(n-1, seenIt) + FibMemoization(n-2, seenIt);
}
console.log(FibMemoization(25)); //75025
console.log(FibIterative(25)); //75025
console.log(FibSmartRecursive(25)); //75025
You can solve this problem without recursion using loops, runtime O(n):
function nthFibo(n) {
// Return the n-th number in the Fibonacci Sequence
const fibSeq = [0, 1]
if (n < 3) return seq[n - 1]
let i = 1
while (i < n - 1) {
seq.push(seq[i - 1] + seq[i])
i += 1
}
return seq.slice(-1)[0]
}
// Using Recursion
const fib = (n) => {
if (n <= 2) return 1;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(4)) // 3
console.log(fib(10)) // 55
console.log(fib(28)) // 317811
console.log(fib(35)) // 9227465

Categories

Resources