finding the nth prime javascript - javascript

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)

Related

Using forEach Loop Generating prime number in Javascript between 1 to 50 [duplicate]

This question already has answers here:
Check Number prime in JavaScript
(47 answers)
Closed 2 years ago.
Here's my code but my answer is not that which i want..
Please Check This and give me a solution to get prime number using Foreach Loop b/w 1-50
Thanks In Advance :)
function isPrime(num) {
for ( var i = 2; i < num; i++ ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}
var txt = "";
function shown(n) {
var arr = [2];
arr.forEach(myFunction);
document.getElementById("foreach").innerHTML = txt;
// document.getElementById('forLoop').innerHTML = arr; // use arr result on your own
}
function myFunction(arr, index, array) {
var i;
var arr = [2];
if ( isPrime(i) ) {
arr.push(i);
}
txt += arr + "<br>";
}
shown(50);
This is probably a too-advanced answer for a homework of this level, but technically it follows the rules (use Array.forEach) and it works.
The primes() generates new primes based on previous primes. So it won't test the reminder of all integers, thus more effecient. There are several arrow function uses, too, to keep things short. If you indeed use this answer, please try to read the relevant documentations and learn:
Iterators and Generators
Arrow function expressions
for...of
Template literals
Seriously, try to think step-by-step. That's how you learn anything.
function* primes() {
const previous = [];
for (let i = 2; true; i++) {
let isPrime = true;
for (let p of previous) {
if (i % p === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
previous.push(i);
yield i;
}
}
}
function* takeUntil(cb, iter) {
for (let val of iter) {
if (cb(val)) {
return;
}
yield val;
}
}
function showArrayIn(arr, container) {
arr.forEach(p => container.innerHTML += `${p},<br/>`); // technically, we used Array.forEach.
}
showArrayIn(
// get the prime number array declarativly
Array.from(takeUntil(n => n >= 50, primes())),
// show in the container specified
document.getElementById("results")
);
Primes:
<div id="results"></div>
function primeFactorsTo(max)
{
var store = [], i, j, primes = [];
for (i = 2; i <= max; ++i)
{
if (!store [i])
{
primes.push(i);
for (j = i << 1; j <= max; j += i)
{
store[j] = true;
}
}
}
return primes;
}
console.log(primeFactorsTo(5));
console.log(primeFactorsTo(15));
I Think so this is the correct answer which i deserve..
It is code lover short and aggressive
function primes(limit)
{
var prime=[], i=1;
while (++i < limit+1) prime.reduce((a,c)=>(i%c)*a,1) && prime.push(i);
prime.unshift(2);
return prime;
}
[50].forEach(n=>document.getElementById('foreach').innerHTML=(`${primes(n)}`));
Consider the following example.
function isPrime(num) {
if (num === 1) {
return false;
} else if (num === 2) {
return true;
} else {
for (var x = 2; x < num; x++) {
if (num % x === 0) {
return false;
}
}
return true;
}
}
function shown(n) {
var list = [];
for (var i = 1; i <= n; i++) {
list.push(i);
}
list.slice().reverse().forEach(function(n, k, o) {
if (!isPrime(n)) {
list.splice(o.length - 1 - k, 1);
}
});
document.getElementById("show").innerHTML = list;
}
shown(50);
Prime: <p id="show"></p>

Finding the prime number. how to improve efficiency of my code

So i am doing Euler problems, and i got to problem asking to find 10001st prime number. i did it like this. From what i can see it has O n^2. Codepen didnt like the time it took and thought it was an infinite loop, had to run on another compiler, my question is there anyway to improve this?
isPrime=(num)=>{
if(num<=1){
return false;
}
for(let i=2;i<num;i++){
if(num%i == 0){
return false;
}
}
return true;
}
findPrime=()=>{
let count=0;
let number = 1;
let prime=0;
while(count != 10001){
let result = isPrime(number);
if(result === true){
count++;
prime = number;
}
number++;
}
return prime;
}
Takes around 1/60 time in node.js and around 1/140 here in Chrome comparing to your original without additional optimisations on my machine, but has a bit more complex setup...
var primes = [2, 3]; // lets start with some basic
function myPrimes(no, mapSize) {
var nonPrimeMap = {};
var pos = 0;
var pos2 = 4;
while (pos < no) {
var s = primes[pos++];
for (var x = s * 2; x < mapSize; x += s) nonPrimeMap[x] = 1;
do {
if (nonPrimeMap[pos2]) pos2++;
else {
primes.push(pos2++);
break;
}
} while (true);
}
}
function runTest() {
var a = new Date();
myPrimes(9999, 110000);
var c = new Date();
console.log(primes[primes.length - 1], c - a); // My test timespans in ms
var b = findPrime();
a = new Date();
console.log(b, a - c); // Your
}
isPrime = (num) => {
if (num <= 1) {
return false;
}
for (let i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
};
findPrime = () => {
let count = 0;
let number = 1;
let prime = 0;
while (count != 10001) {
const result = isPrime(number);
if (result === true) {
count++;
prime = number;
}
number++;
}
return prime;
};
runTest();

Javascript Function Issues for Prime Numbers

So what I'm trying to do is use a function that prompts to enter a number and then prints all prime numbers up till that number. I have the code as far as I know but I keep getting an error that the bracket following prime(num) is wrong. Not sure what I'm doing wrong here, would appreciate any help.
function p5Bela() {
var num = prompt("Please enter a number: ", "");
for (i = 2; i <= num; i++) {
if (prime(i)==true) {
alert(i);
}
}
prime(num) {
var flag = true;
var d = 2;
while (flag==true && d <= num/2) {
if (num%d == 0) {
flag = false;
}
d++;
}
return flag;
}
}
Simplest Way
function isPrime(num) {
for(var i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
With the ES6 syntax:
const isPrime = num => {
for(let i = 2; i < num; i++)
if(num % i === 0) return false;
return num > 1;
}
You can also decrease the complexity of the algorithm from O(n) to O(sqrt(n)) if you run the loop until square root of a number:
const isPrime = num => {
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return false;
return num > 1;
}

"Steps in Primes" of Codewars

I got problems when doing "Steps in Primes" of Codewars.
Make function step(g,m,n) which g=step >= 2 , m=begin number >=2,
n=last number>= n. Step(g,m,n) will return the first match [a,b] which
m < a,b is prime < n and a+g=b.
I did right in basic test cases but when i submit , i got infinity loop somewhere. Can anyone give me suggestion?
function isInt(n) {
if(typeof n==='number' && (n%1)===0) {
return true;
}
else return false;
}
function step(g, m, n) {
if(isInt(g) && isInt(m) && isInt(n) &&g >= 2 && m >= 2 && n>=m) {
var p=[];
var ans=[];
for (var temp=m; temp<=n;temp++)
{
var a=0;
for (var chk=2; chk<temp-1;chk++)
if (temp%chk===0) a++;
if (a===0) p.push(temp);
}
for (var a=0;a<p.length-1;a++)
{
for (var b=a+1;b<p.length;b++)
if (p[b]===(p[a]+g)) return [p[a],p[b]];
}
}
return "nil";
}
this code might help you
function gap(g, m, n) {
var prime-numbers = [];
var final = [];
var prime;
for (var i = m; i <= n; i++) {
prime = true;
for (var j = 2; j < i / 2; j++) {
if (i % j === 0) {
prime = false;
}
}
if (prime) {
prime-numbers.push(i);
}
}
prime-numbers.forEach(function(prime, index) {
if (prime + g === prime-numbers[index + 1]) {
final.push(prime, prime-numbers[index + 1]);
}
});
if (final) return final.slice(0,2);
else return null;
}

Project Euler #23 in JS

My results for numbers between 1 and 28321 (limit)
sum of all numbers: 395465626
sum of all abundant numbers: 392188885
sum of all non abundant numbers: 3276741 (correct answer is 4179871)
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++)
{
if (divisors(i))
{abundent[k] = i; k++};
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++){
for (var j = i; j < abundentCount; j++){
if (abundent[i] + abundent[j] <= upperLimit){canBeWrittenAsAbundant[abundent[i]+abundent[j]] = true;}
else {
break;
}
}
}
for (i=1; i <= upperLimit; i++){
if (canBeWrittenAsAbundant[i] == true){continue;}
else {canBeWrittenAsAbundant[i] = false;}
}
var sum = 0;
for (i=1; i <= upperLimit; i++)
{
if (!canBeWrittenAsAbundant[i]){
sum += i;
}
}
console.log(sum);
I'm using http://www.mathblog.dk/project-euler-23-find-positive-integers-not-sum-of-abundant-numbers/ as guidance, but my results are different. I'm a pretty big newb in the programming community so please keep that in mind.
You do not need to calculate the sum of all numbers using a cycle, since there is a formula, like this:
1 + 2 + ... + number = (number * (number + 1)) / 2
Next, let's take a look at divisors:
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
You initialize sum with 1, since it is a divisor. However, I do not quite understand why do you iterate until the square root instead of the half of the number. For example, if you call the function for 100, then you are iterating until i reaches 10. However, 100 is divisible with 20 for example. Aside of that, your function is not optimal. You should return true as soon as you found out that the number is abundant. Also, the name of divisors is misleading, you should name your function with a more significant name, like isAbundant. Finally, I do not understand why do you decrease square root if number happens to be its exact square and if you do so, why do you have this check in the cycle. Implementation:
var isAbundant = function(number) {
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) {
sum += i;
if (sum > number) {
return true;
}
}
}
return false;
}
Note, that perfect numbers are not considered to be abundant by the function.
You do not need to store all numbers, since you are calculating aggregate data. Instead, do it like this:
//we assume that number has been initialized
console.log("Sum of all numbers: " + ((number * (number + 1)) / 2));
var abundantSum = 0;
var nonAbundantSum = 0;
for (var i = 0; i <= number) {
if (isAbundant(i)) {
abundantSum += i;
} else {
nonAbundantSum += i;
}
}
console.log("Sum of non abundant numbers: " + nonAbundantSum);
console.log("Sum of abundant numbers: " + abundantSum);
Code is not tested. Also, beware overflow problems and structure your code.
Below is the Corrected Code for NodeJS..
var divisors = function (number) {
sqrtNumber = Math.sqrt(number);
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) { sum += i; }
}
if (sum > number) { return true; }
else { return false; }
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++) {
if (divisors(i)) { abundent[k] = i; k++ };
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++) {
for (var j = i; j < abundentCount; j++) {
if (abundent[i] + abundent[j] <= upperLimit) { canBeWrittenAsAbundant[abundent[i] + abundent[j]] = true; }
else {
break;
}
}
}
for (i = 1; i <= upperLimit; i++) {
if (canBeWrittenAsAbundant[i] == true) { continue; }
else { canBeWrittenAsAbundant[i] = false; }
}
var sum = 0;
for (i = 1; i <= upperLimit; i++) {
if (!canBeWrittenAsAbundant[i]) {
sum += i;
}
}
console.log(sum);

Categories