May be the question is so clear and doesn't need any more explanation but this is examples previous primes:
The previous prime of 19 is ===> 17
The previous prime of 211 is===> 199
My failing trial
const getPreviousPrime = (number) => {
for(let i = number - 1; i >= 2; i--) {
for(let j = 2; j <= Math.sqrt(i); j++ ) {
if(i % j === 0) break
return i
}
}
}
Start by writing assuming you have an isPrime() function.
Then you can write the loop easily.
const getPreviousPrime = (number) => {
for (let i = number - 1; i >= 2; i--) {
if (isPrime(i)) {
return i;
}
}
}
You can find many implementations of isPrime() at Number prime test in JavaScript
Hope this will help you.
const getPreviousPrime = (number) => {
for(let i = number - 1; i >= 2; i--) {
let prime = true;
for(let j = 2; j <= Math.sqrt(i); j++ ) {
if(i % j === 0) {
prime = false
break;
}
}
if (prime == true) {
return i
}
}
return 2;
}
console.log(getPreviousPrime(19))
console.log(getPreviousPrime(211))
Related
I'm aware of the modular arithmetic approach to solve this question, I just took it upon myself to solve it in the more naive way, but I just created an infinite loop somewhere in the inner for loop and there is no way out (Please do not tell me to do it in the standard way, This is just a challenge that I made upon myself)
The function return the size of a maximal subset of S where the sum of any 2 numbers in s’ is not evenly divisible by k.
here is my code that causes an infinite loop, so be careful
function nonDivisibleSubset(arr, k) {
let maxElements = 0;
for (let i = 0; i < arr.length; i++) {
console.log(i);
// arr 1 to (arr.length - 1)
let result = [];
let noOfElements = 0;
for (let j = 0 + 1; j < arr.length; j++) {
console.log(`hi${j}`);
//arr 2 to arr.length
console.log(result.length);
if (
result.length === 0 &&
(arr[i] + arr[j]) % k !== 0
) {
console.log("hi2");
result.push(arr[i], arr[j]);
noOfElements += 2;
} else {
let isDivisible = false;
console.log(`result length: ${result.length}`);
for (let l = 0; l < result.length; l++) {
console.log(l);
if (i !== l && (arr[l] + arr[j]) % 4 === 0) {
isDivisible = true;
break;
}
if (!isDivisible) {
result.push(arr[l]);
console.log(result);
noOfElements += 1;
break; //removing this break will initialize the infinite loop
}
}
}
}
if (noOfElements > maxElements) {
maxElements = noOfElements;
}
}
return maxElements;
}
//initialise
nonDivisibleSubset([19, 10, 12, 10, 24, 25, 22], 4)
The resul array continues to increase in size as the repeat statement spins.
Here is an example of how you can do it:
for (let l = 0, size = result.length; l < size; l++) {
if (i !== l && (arr[l] + arr[j]) % 4 === 0) {
isDivisible = true;
break;
}
if (!isDivisible) {
result.push(arr[l]);
console.log(result);
console.log(result.length);
noOfElements += 1;
break; //removing this break will initialize the infinite loop
}
}
And,
if (i !== l && (arr[l] + arr[j]) % 4 === 0)
Isn't it k, not 4?
if (i !== l && (arr[l] + arr[j]) % k === 0)
I hope it helps.
I'm trying to solve a problem on an educational website platform.
This is the task/problem:
Write a program that finds and prints the biggest prime number which is <= N.
Input
On the first line you will receive the number N
Output
Print the biggest prime number which is <= N
Constraints
2 <= N <= 10 000 000
Examples
If N=13, then the biggest prime number is also 13.
If N=126, then the biggest prime number is also 113.
If N=26, then the biggest prime number is also 23
This is my code, which works fine, but the system does not accept it as fully correct because my code is slow/exceeds the memory limit:
const inputnumber = theNumberN; // Comes dymanically from the system
function getPrimes(max) {
let sieve = [];
let primes = [];
for (let i = 2; i <= max; ++i) {
if (!sieve[i]) {
primes.push(i);
for (let j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
let result = getPrimes(inputnumber);
let biggest = Math.max(...result);
console.log(biggest);
So, how can this be solved?
Can you offer a faster logic/algorithm
Assuming you are looking for only the biggest prime in a given range (2 <= N <= 10 000 000), the "simple" approach might actually be faster, since spread in primes below 10 000 000 is preety low (hence, the i-loop won't do so many rotations, disclaimer: this will not necessarly be true for all ranges).
function getBiggestPrime(max) {
let sieve = [];
let primes = [];
for (let i = 2; i <= max; ++i) {
if (!sieve[i]) {
primes.push(i);
for (let j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes[primes.length - 1];
}
function getBiggestPrimeTwo(max){
let biggestPrime = 1;
for (let i = max; i >= 2; i--){
let isPrime = true;
for (let j = 2; j < i; j++){
if (i % j == 0){ //break the loop, the number is not a prime
isPrime = false;
break;
}
}
if (isPrime){
biggestPrime = i;
break;
}
}
return biggestPrime;
}
function runTests(val, times){
var t0, t1, res, testStep;
testStep = val / times;
t0 = performance.now();
for (let i = 1; i <= times; i++){
res = getBiggestPrime(testStep*i);
}
t1 = performance.now();
console.log("Test1: " + res + ", took: " + (t1-t0) + "msec");
t0 = performance.now();
for (let i = 1; i <= times; i++){
res = getBiggestPrimeTwo(testStep*i);
}
t1 = performance.now();
console.log("Test2: " + res + ", took: " + (t1-t0) + "msec");
}
runTests(10000000, 50);
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 <=.
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) {
the functions below are supposed to spit out the nth prime number. However, it keeps on spitting out 3. Can somebody please help? Cheers, Anthony
function Prime(num) {
output = true
for (i=2 ; i<num ; i++) {
if (num%i === 0) {
output = false ; break
}
}
return output
}
function PrimeMover(num) {
var count = 0
for (i=2 ; i<10000 ; i++) {
if (Prime(i) === true) {
count = count + 1
}
if (count === num) {
return i
break
}
}
}
You have created loop counter i in global scope.so both PrimeMover and Prime mutates same global i.In every iteration ,PrimeMover assigns i=2.After that Prime assigns i=2.your i variable's value will be changed between 2 and 3.use local loop counter variable var i=0;
function Prime(num) {
output = true
for (var i=2 ; i<num ; i++) { //var i=2
if (num%i === 0) {
output = false ; break
}
}
return output
}
function PrimeMover(num) {
var count = 0
for (var i=2 ; i<10000 ; i++) { //var i=2
if (Prime(i) === true) {
count = count + 1
}
if (count === num) {
return i
break
}
}
}
For minimal code lovers,
function nthprime(n)
{
var prime=[], i=1
while (i++ && prime.length<n) prime.reduce((a,c)=>(i%c)*a,2) && prime.push(i)
return prime.length?prime.pop():-1
}
[-1,0,1,2,3,5,10,100].forEach(n=>console.log(`nthprime(${n})=${nthprime(n)}`))
function main(inp) {
var count = 0;
for (var i = 2; i <= 100000; i++) {
if (isPrime(i)) count = count + 1;
if (count == inp) return i;
}
}
function isPrime(i) {
for (var j = 2; j < i; j++) {
//instead of `j < i` it can be reduced using other conditions
if (i % j == 0) {
return false
}
}
return true
}
main(5) // any number
This might be a bit more optimal
function nthPrime(n) {
var P = 0;
function isPrime(x) {
var isPrime= true;
for (var d = 2; d <= Math.sqrt(x); d++) {
if((x/d) % 1 == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
for (var i = 1; 0 < n; i++) {
if(isPrime(i)) {
P = i; n--;
}
// we can skip the even numbers
if(3 <= i){
i++;
}
}
return P;
}
Try this
var pos=10001;
console.log(primeNumforPos(pos));
function primeNumforPos(pos){
var num=2,curPos=0;
while(curPos<=pos){
if(isPrime(num)){
curPos++;
}
if(curPos==pos){
return num;
}else{
num++;
}
}
}
function isPrime(num){
for(var i=2;i<=Math.sqrt(num);i++){
if(num%i==0){
return false;
}
}
return true;
}
So, I decided to optimise the hell out of the code (cuz why not). It is almost 6 times as fast as that of ppseprus (297ms vs 1773ms in nth_prime(100000)).
let primes = [2, 3];
const nth_prime = (n) => {
if (n <= primes.length) return primes[n - 1]; // handle values which have been cached
let i = 1;
while (1){
const a = 6 * i - 1, b = 6 * i + 1, a_limit = Math.sqrt(a), b_limit = Math.sqrt(b); // the 6n - 1 and 6n + 1 rule for primes
let a_prime = true, b_prime = true;
i++;
// prime check
for (const prime of primes){
if (prime > a_limit) break;
if (a % prime == 0){
a_prime = false;
break;
}
}
if (a_prime){
if (primes.length + 1 == n) return a;
primes.push(a); // cache
}
for (const prime of primes){
if (prime > b_limit) break;
if (b % prime == 0){
b_prime = false;
break;
}
}
if (b_prime){
if (primes.length + 1 == n) return b;
primes.push(b); // cache
}
}
}
const findPrime = num => {
let i, primes = [2, 3], n = 5
const isPrime = n => {
let i = 1, p = primes[i],
limit = Math.ceil(Math.sqrt(n))
while (p <= limit) {
if (n % p === 0) {
return false
}
i += 1
p = primes[i]
}
return true
}
for (i = 2; i <= num; i += 1) {
while (!isPrime(n)) {
n += 2
}
primes.push(n)
n += 2
};
return primes[num - 1]
}
console.time('Time')
let x = findPrime(9999)
console.timeEnd('Time')
console.log(x)