Find the next greater prime of a given number - javascript

Here's the code i wrote to solve the problem:
let isPrime = function(n) {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
};
function nextPrime(num) {
let newNum = num;
for (let i = 0; i < newNum; i++) {
if (!isPrime(newNum)) {
newNum += 1;
} else if (isPrime(newNum)) {
return newNum;
}
}
};
My plan is:
// increment the num by 1 and check if that new num is prime;
// if not, increment again and check again. Repeat the process untill prime is found.
Input and (expected output is commented):
console.log(nextPrime(2)); // 3
console.log(nextPrime(3)); // 5
console.log(nextPrime(7)); // 11
console.log(nextPrime(8)); // 11
console.log(nextPrime(20)); // 23
console.log(nextPrime(97)); // 101
The output i'm getting;
2
3
7
11
23
97
I'd like to know where exactly my implementation is wrong. Also, i'd like the code to be without fancy methods because i'm new to all this. Thank you!

The assignment newNum = num precisely does not make newNum a new number, but the same ! This is why the function returns immediately when the input argument is prime.
By the way, the loop would be much cleaner as
do
{
newNum += 1;
} while (!isPrime(newNum));

function nextPrime(previousPrime) {
const value = previousPrime;
if (value > 2) {
var i, q;
do {
i = 3;
value += 2;
q = Math.floor(Math.sqrt(value));
while (i <= q && value % i) {
i += 2;
}
} while (i <= q);
return value;
}
return value === 2 ? 3 : 2;
}

Related

Project Euler Largest Prime Factor bug in Javascript

I am new to javascript and struggling mightily to understand why this doesn't work.
function largestPrimeFactor(num) {
var primeFactors = [];
for (var i = 2; i < num; i++) {
// check if iter i is prime
if (checkIfPrime(i)) {
// if so, see if its a factor of num
while (num % i === 0) {
num /= i;
primeFactors.push(i);
console.log(primeFactors);
console.log(num);
}
}
if (num === 1) {
// return Math.max.apply(Math, primeFactors)
console.log(primeFactors);
console.log(Math.max.apply(Math, primeFactors));
}
}
}
function checkIfPrime(num) {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
console.log(largestPrimeFactor(13195));
The final console.log never goes off for the last prime number 29. I never enter the last if(num === 1) case either, which I also don't know why...
When I iterate up to 29, checkIfPrime(i) should be true, and then after 29 / 29 sets num to 1, the last if case should work too.
Why is this not working??
Second Q - is
return Math.max.apply(Math, primeFactors)
the right way to return the max value from an array of integers?
Thanks!
for(var i = 2; i < num; i++) { // line 3
So if num is 29, i can only go to 28. Should change the < to <=.

Find out which one of the given numbers differs from the others for Javascript

I'm trying to solve this exercise. There is a string of numbers and among the given numbers the program finds one that is different in evenness, and returns a position of this number. The element has to be returned by its index (with the number being the actual position the number is in). If its index 0, it has to be returned as 1. I have this so far but it's not passing one test. I'm not too sure why because it feels like it should. Is anyone able to see what the error is? Any help is appreciated!
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var position = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
position = num.indexOf(num[i]) + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
position = num.indexOf(num[i]) + 1;
}
}
}
return position;
}
iqTest("2 4 7 8 10") output 3
iqTest("2 1 2 2") output 2
iqTest("1 2 2") outputs 2 when it should be 1
The simplest way is to collect all even/odd positions in subarrays and check what array has the length 1 at the end:
function iqTest(numbers) {
numbers = numbers.split(' ');
var positions = [[], []];
for (var i = 0; i < numbers.length; i++) {
positions[numbers[i] % 2].push(i + 1);
}
if(positions[0].length === 1) return positions[0][0];
if(positions[1].length === 1) return positions[1][0];
return 0;
}
console.log(iqTest("2 4 7 8 10"))
console.log(iqTest("2 1 2 2"))
console.log(iqTest("1 2 2"))
console.log(iqTest("1 3 2 2"))
Your code is overly complex.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately. Then, find the first number that doesn't match it.
function iqTest(numbers) {
numbers = numbers.split(" ");
var parity = numbers.shift() % 2;
for( var i=0; i<numbers.length; i++) {
if( numbers[i] % 2 != parity) {
return i+2; // 1-based, but we've also skipped the first
}
}
return 0; // no number broke the pattern
}
That being said, iqTest("1 2 2") should return 2 because the number in position 2 (the first 2 in the string) is indeed the first number that breaks the parity pattern (which 1 has established to be odd)
You have to define which "evenness" is the different one. Use different counters for the two cases, and return -1 if you don't have a single different one. Something like this:
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var positionOdd = 0;
var positionEven = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
positionOdd = i + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
positionEven = i + 1;
}
}
}
if (odd == 1)
return positionOdd;
else if (even == 1)
return positionEven;
else
return -1;
}
Note that, if you have exactly a single even number and a single odd one, the latter will be returned with the method of mine. Adjust the logic as your will starting from my solution.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately.
Then, find the first number that doesn't match it.
function iqTest(numbers){
// ...
const numArr = numbers.split(' ');
const checkStatus = num => (parseInt(num) % 2) ? 'odd' : 'even';
const findUniqueStatus = array => {
let numEvens = 0;
array.forEach(function(value){
if (checkStatus(value) == 'even') { numEvens++; }
});
return (numEvens === 1) ? 'even' : 'odd'
}
let statuses = numArr.map(checkStatus),
uniqueStatus = findUniqueStatus(numArr);
return statuses.indexOf(uniqueStatus) + 1;
}
}
public static int Test(string numbers)
{
var ints = numbers.Split(' ');
var data = ints.Select(int.Parse).ToList();
var unique = data.GroupBy(n => n % 2).OrderBy(c =>
c.Count()).First().First();
return data.FindIndex(c => c == unique) + 1;
}

Javascript loop for estructure

i have to solve the following function: "x" represent a number of cycles. One cycle sums +1 and then multiply the result *2. For example:
0 cycles = 0 + 1 = 1 (result)
1 cycles = 1 * 2 = 2 (result)
2 cycles = 2 + 1 = 3 (result)
3 cycles = 3 * 2 = 6 (result)
4 cycles = 6 + 1 = 7 (result) and so on.
I have this function:
function final(x) {
for (var i = 0; i < x; i++) {
var result = x[i] * 2 + 1
}
return result;
}
Can you help me out?
If you want to store the results, you can use answer by #Kornflexx. If not, you can directly calculate the value :
function final (x) {
var t = (4 << (x / 2)) - 2;
return x % 2 ? t : t / 2;
}
Note that if x is large you will quickly pass the int limit and would then need to deal with big integers
This should work if you don't care of the fact that the for start at 1.
function final(x) {
var result = [];
result[0] = 1;
for (var i = 1; i < x; i++) {
result[i] = i % 2 ? result[i - 1] * 2 : result[i - 1] + 1;
}
return result;
}
If you only require the final result of the function then the following will achieve that for you.
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
if (x % 2 === 0) {
result = result + 1;
} else {
result = result * 2;
}
}
return result;
}
Thanks for your help, the solution finally was this:
function final(x){
var result = 0;
for (var i = 0; i < x; i++){
if (i % 2 === 0){
result = result * 2 + 1;}
else{
result = (result + 1);}
}
return result+1;
}
Just for variety, you can have this short form
function final(x) {
var result = 0;
for (var i = 0; i < x; i++) {
result = x % 2 == 0 ? result + 1 : result * 2
}
console.log(x,result)
return result;
}
final(3)

Find the sum of all the primes below two million using java script

I am trying this code
var sum = 0
for (i = 0; i < 2000000; i++) {
function checkIfPrime() {
for (factor = 2; factor < i; factor++) {
if (i % factor = 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
}
document.write(sum);
I am getting this error:
Invalid left-hand side in assignment
Change if(i % factor = 0) to if( i % factor == 0) and remove the function checkIfPrime() inside the for loop.
var sum = 0
for (i = 0; i < 2000000; i++) {
for (factor = 2; factor < i; factor++) {
if (i % factor == 0) {
sum = sum;
}
else {
sum += factor;
}
}
}
document.write(sum);
The function inside the loop is pointless.
it looks like your code outputs wrong result, for example prime numbers below 6 are 2, 3 and 5, their sum is 10, your code outputs 14 in this case.
Here is another code which outputs sum of primes below max value:
var sieve = [], primes = [], sum = 0, max = 5;
for (var i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
sum += i;
for (var j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
console.log(sum);
credit to How to find prime numbers between 0 - 100?
function sumPrimes(num) {
var sum = 0;
for (var i = 2; i < num; i++) {
if (isPrime(i)) {
sum += i;
console.log(sum);
}
}
return sum;
}
function isPrime(num) {
if (num <= 1) return false;
else if (num <= 3) return true;
else if (num % 2 == 0 || num % 3 == 0) return false;
var i = 5;
while (i * i <= num) {
if (num % i == 0 || num % (i + 2) == 0) return false;
i += 6;
}
return true
}
console.log(sumPrimes(2000000));
Well, I did with 250 otherwise my screen would have frozen. First of you have to single out the prime numbers after placing them inside an empty Array, which I called primeNumbers from 2 to whatever number you want. Then I create a function that would filter the prime numbers and then add them all with a reduce method inside of another variable called sum and return that variable.
var primeNumbers =[];
for(var i = 2; i < 250; i++){
primeNumbers.push(i);
}//for loop
function isPrime(value){
for(var x=2; x< value; x++){
if(value % x===0){
return false;
}
}//for loop
return true;
}//function isPrime to filter
var sum = primeNumbers.filter(isPrime).reduce(function(acc, val) {
return acc + val;
}, 0);
console.log(sum);
when you are using a variable inside the loop you need to declare them. You have two points in this case
i is not declared
factor is not declare
Your if (i % factor = 0) is wrong, as pointed by some people above.
Also, you never call the checkIfPrime() method. I don't why you created them. Also, I improved your checkIfPrime() method. Please call sumOfPrimes() method in the code below and it should work. You can modify it according to your need
function sumOfPrimes()
{
var sum =0;
for (var i = 0; i < 2000000; i++)
{
var temp = Math.sqrt(i);
for (var factor = 2; factor < temp; factor++)
{
if (i % factor === 0)
{
sum += factor;
}
}
}
console.log(sum);
}
Try changing this line if (i % factor = 0) {
to
if (i % factor == 0) {

How can I declare a counter inside of my recursive function? (Additive Persistence: Coderbyte)

While working through some Coderbyte challenges, I was able to solve the following problem recursively, but was hoping to get some feedback on how I can improve it.
Have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit.
For example: if num is 2718 then your program should return 2 because
2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.
My submitted, working recursive solution is below. How can I place "count" into my function without letting it get "reset" every time I recurse?
var count = 0;
function AdditivePersistence(num) {
count = 0;
if (num < 10) {
return count;
}
if (num > 10) {
count++;
AdditivePersistence('' + num.split("").reduce(function(a,b) {
return parseInt(a) + parseInt(b)
}));
}
}
Here's my broken attempt at moving the counter within the function... would appreciate any pointers for my beginner-self. Beyond just fixing the code, I'd love it if there are other great methods for solving this puzzle!
function AdditivePersistence(num) {
var count = 0;
(function recurse(num) {
if (num < 10) {
return count;
}
if (num > 10) {
count++;
recurse('' + num.split("").reduce(function(a,b) {
return parseInt(a) + parseInt(b);
}));
}
})();
return count;
}
Edit: I just tried with a while loop below
function AdditivePersistence(num) {
var count = 0;
while (num >= 10) {
count++
num = num.toString().split('').reduce(function(a,b) {
return parseInt(a) + parseInt(b);
})}
return count;
}
Many thanks in advance!
The idea is simple
AdditivePersistence(n):
if n < 10
return 0
else
return 1 + AdditivePersistence(sum-of-digits(n))
Strictly speaking, there's no need for the recursion here - that's essentially a normal while loop.
I'm going to extend #georg's answer and provide a full implementation
var additivePersistance = (function () {
function sumOfDigits (n) {
var ret = 0;
n.toString().split('').forEach(function (i) {
ret += parseInt(i, 10);
});
return ret;
}
return function additivePersistance (n) {
if (n < 10) {
return 0;
}
return additivePersistance(sumOfDigits(n)) + 1;
}
}());
This implementation hides the sumOfDigits as a helper method using a closure.
additivePersistance(2718); // 2
This closure idea can also serve to create a psudo static variable in the recursive function. Follow this form.
var func = (function () {
var staticCounter = 0;
return function func() {
if (staticCounter++ > 20) {
return 0;
}
return func() + 1;
};
}());
Here the body of the inner func method is using the variable staticCounter accross all calls to the outter func.
var count = 0;
function AdditivePersistence(num)
{
// make the number into a string so that each digit can be taken
var num_string = num.toString();
// this will hold each digit
var numbers = [];
// iterate through each digit as a character
for(var i = 0; i < num_string.length; ++i)
{
// add the character converted to a number into the numbers array
numbers.push(parseInt(num_string[i]));
}
// this will hold the value of all the digits added together
var total = 0;
// iterate through the digits
for(var i = 0; i < numbers.length; ++i)
{
// add each digit to the total
total += numbers[i];
}
// if larger than the total
if(total > 10)
{
// increase the count
++count;
// redo it again
AdditivePersistence(total);
}
else
{
// return the total amount of tries
return (++count);
}
}

Categories