Write a Boolean function named isPrime which takes an integer as an argument and returns true if the argument is a prime number of false otherwise. Generate 100 random numbers and display the results of checking each one for primality.
This is supposed to output the random numbers that are prime (after the true or false check) but I am getting the results of 2 sets of numbers in order.
Here is my code:
var arr = []
while(arr.length < 100){
var randomnumber=Math.ceil(Math.random()*100)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
console.log(arr);
for(i = 0; i < 100; i++){
if(isPrime(i)) console.log(i);
}
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i==0)
return false;
}
return true;
}
You need to check for primality of arr[i] instead of i:
for(i = 0; i < 100; i++){
if(isPrime(arr[i])) console.log(arr[i]);
}
function isPrime(value) {
for(var i = 2; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
}
function myFunction() {
for(var i = 0; i < 100; i++) {
$('#demo').append('<div>'+i+'*****'+isPrime(i)+'</div>');
}
}
try it in an html page and dont forget to add jquery
The below code part, you are trying to check the numbers from 0 to 100
for(i = 0; i < 100; i++){
if(isPrime(i)) console.log(i);
}
But you should check the arr array one by one
for(i = 0; i < 100; i++){
if(isPrime(arr[i])) console.log(arr[i]);
}
Using an object to store the numbers let's you avoid the loop to check for duplicates and moving the check for isPrime () let's you skip the second loop. (Your issue was, as #Andrea pointed out, not passing arr [i] to isPrime)
var myRandObj = {};
var randomNumber = 0;
for (var i = 0; i < 100; i++) {
do {
randomNumber = Math.ceil(Math.random() * 100);
} while (typeof myRandObj[randomNumber] !== 'undefined');
myRandObj[randomNumber] = 0;
if (isPrime (randomNumber))
console.log (randomNumber);
}
console.log(arr) is printing the entire array to the console. Remove that line to debug further.
var arr = []
for(x = 0; x < 100; x++){
arr[x] = Math.ceil(Math.random()*100)
}
for(i = 0; i < 100; i++){
if(isPrime(arr[i])) console.log(arr[i]);
}
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i==0)
return false;
}
return true;
}
I am working on an excercise to sum all prime numbers from 2 to the parameter. I have worked this far in the code, but am stuck. I believe by using the splice function, I am actually skipping an element because of a changed indices.
function sumPrimes(num) {
var primearray = [];
var sum = 0;
for(var i =2; i <= num; i++){
primearray.push(i);
}
for(var j = 0; j < primearray.length; j++) {
console.log(primearray[j]);
if ((primearray[j]%2===0) && (primearray[j] >2)) {
primearray.splice(j,1);
} else if ((primearray[j]%3===0) && (primearray[j] > 3)) {
primearray.splice(j,1);
console.log(primearray);
} else if ((primearray[j]%5===0) && (primearray[j] > 5)) {
primearray.splice(j,1);
} else if ((primearray[j]%7===0) && (primearray[j] > 7)) {
primearray.splice(j,1);
}
}
sum = primearray.reduce();
return sum;
}
sumPrimes(30);
I haven't utilized the reduce function yet because I am still working on the if else statements.
I found a pretty good solution to the same problem. afmeva was spot on. This is how it works.
function isPrime(val){
//test if number is prime
for(var i=2; i < val; i++){
if(val % i === 0){
return false;
}
}
return true;
}
In the above code we accept a number to determine whether or not it is prime. We then loop from two all the way up until our number minus one because we know that our number will be divisible by itself and one. If the remainder of our value with the current loop value is zero then we know it is not prime so break out and say so.
This article explains very well
function sumPrimes(num) {
var answer = 0;
//loop through all numbers from 2 to input value
for(var i=2; i <= num; i++){
//sum only prime numbers, skip all others
if(isPrime(i)){
answer += i;
}
}
return answer;
}
sumPrimes(977); // 73156
Here's another good resource
function sumPrimes(num) {
let arr = Array.from({length: num+1}, (v, k) => k).slice(2);
let onlyPrimes = arr.filter( (n) => {
let m = n-1;
while (m > 1 && m >= Math.sqrt(n)) {
if ((n % m) === 0)
return false;
m--;
}
return true;
});
return onlyPrimes.reduce((a,b) => a+b);
}
sumPrimes(977);
I have seen lots of people putting all prime numbers into arrays and in order to check if a number is prime, they check from 2 to the number to see if there's a remainder.
You only need to check odd numbers, and only need to count to half the number because a number can't be divisible by any number greater than it has.
Here's my solution:
function sumPrimes(num){
var sum = num>=2?2:0;
for(var i=3;i<=num;i+=2){
var isPrime=true;
for(var j=3;j<(i/2);j++){
if (i%j==0)
{
isPrime=false;
break;
}
}
sum+=isPrime?i:0;
}
return sum;
}
Note: I started from j=2 because we are only checking odd numbers, so they'd never be divisible by 2.
function sumPrimes(num) {
var sumArr= [];
for(var i=0;i<=num;i++){
if(isPrime(i))
sumArr.push(i);
}
sumArr = sumArr.reduce(function(a,b){
return a+b;
})
return sumArr;
}
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i < num; i++) {
if(num%i === 0)
return false;
}
return true;
}
sumPrimes(10);
something like this?
function isPrime(_num) {
for(var i = 2; i < _num; i++) {
if(!(_num % i)) {
return false
}
}
return true;
}
function sumPrimes(_num) {
var sum = 0;
for(var i = 2; i <= _num; i++) {
if(isPrime(i)) {
sum += i;
}
}
return sum;
}
sumPrimes(20) // 77
sumPrimes(5) // 10
You could do this as well.
function sumPrimes(num) {
var sum = 0;
for (var i = 0; i <= num; i++) {
if (isPrime(i)) {
sum += i;
}
}
return sum;
}
function isPrime(n) {
if (n < 2) { return false; }
if (n !== Math.round(n)) { return false; }
var result = true;
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
result = false;
}
}
return result;
}
Here's my solution. I hope you find it easy to interpret:
function sumPrimes(num) {
// determine if a number is prime
function isPrime(n) {
if (n === 2) return true;
if (n === 3) return true;
if (n % 2 === 0) return false;
if (n % 3 === 0) return false;
var i = 5;
var w = 2;
while (i * i <= n) {
if (n % i === 0) {
return false;
}
i += w;
w = 6 - w;
}
return true;
}
// subtract 1 for 'not being prime' in my context
var sum = isPrime(num) ? num - 1 : -1;
for (var x = 0; x < num; x++) {
if (isPrime(x) === true) {
sum += x;
}
}
return sum;
}
here is my solution to sum of n prime number
function sumOfNPrimeNumber(num){
var sum = 0;
const isPrime = function(n){
if (isNaN(n) || !isFinite(n) || n%1 || n<2) {
return false;
}
if (n%2==0){
return (n==2);
}
var sqrt = Math.sqrt(n);
for (var i = 3; i < sqrt; i+=2) {
if(n%i == 0){
return false;
}
}
return true;
}
const getNextPrime = function* (){
let nextNumber = 2;
while(true){
if(isPrime(nextNumber)){
yield nextNumber;
}
++nextNumber;
}
}
const nextPrime = getNextPrime();
for (var i = 0; i < num; i++) {
sum = sum + nextPrime.next().value;
}
return sum;
}
console.log(sumOfNPrimeNumber(3));
All the above answers make use of helper functions or aren't time efficients.
This is a quick, recursive solution in O(n) time:
// # signature int -> int
// # interpr: returns sum of all prime integers <= num
// assume: num is positive integer
function sumPrimes(num) {
if (num <= 2) {
return 2;
}
let i = 2;
while (i < num) {
if (num % i === 0) {
return sumPrimes(num - 1)
}
i++;
}
return num + sumPrimes(num - 1)
}
// test
sumPrimes(10); // -> 17
function prime_sum(num){
let count=0; *//tracks the no of times number is divided perfectly*
for(let i=1;i<=num;i++){ *//from 1 upto the number*
if(num%i==0){count++};
}
if(count===2){return "Prime"};
return{"Not prime"};
}
console.log(prime_sum(10));//expected output is 17**
//the code receives a number,checks through the range and returns prime if it meets the condition
The following solution uses the Eratosthenes Sieve to sum all prime numbers lower than or equal to num. The first for loop fills an array with size equal to num with true. The second for loop sets to false all non-prime numbers in the array. Then, the last for loop simply iterates through the array to sum all the array indexes i for which the value in the array, i.e., array[i], is equal to true.
/**
* Sum all primes lower or equal than n.
* Uses the Eratosthenes Sieve to find all primes under n.
*/
function sumPrimes(num) {
let array = [];
let output = 0;
// Fill an array of boolean with 'true' from 2 to n.
for (let i = 0; i <= num; i++) {
array.push(true);
}
// Set all multiples of primes to 'false' in the array.
for (let i = 2; i <= Math.sqrt(num); i++) {
if (array[i]) {
for (let j = i * i; j <= num; j += i) {
array[j] = false;
}
}
}
// All array[i] set to 'true' are primes, so we just need to add them all.
for (var i = 2; i <= num; i++) {
if (array[i]) {
output += i;
}
}
return output;
}
console.log(sumPrimes(10)); // 17
console.log(sumPrimes(977)); // 73156
console.log(sumPrimes(250_000_000)); // 197558914577
function sumPrimes(num) {
let output = 0;
// check if num is a prime number
function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
}
}
return true;
}
for (let i = 2; i <= num; i++) {
if (isPrime(i)) {
output += i;
}
}
return output;
}
console.log(sumPrimes(10)); // 17
This is what I've done to get primes. I don't know if it's the most efficient, but it works. This is in Java, but can be easily converted to JavaScript. Hopefully this will help point you in the right direction.
final int TOTAL = 10;
int primes[] = new int[TOTAL];
int arrPos = 2;
boolean prime = false;
primes[0] = 2;
for (int i = 2; i < TOTAL; i++) {
prime = false;
int sqrt = (int) Math.sqrt(i);
for (int j = 1; j < arrPos && primes[j] < sqrt; j++) {
if (i % primes[j] != 0) {
prime = true;
} else {
prime = false;
break;
}
}
if (prime == true) {
primes[arrPos] = i;
arrPos++;
}
}
What is a fast and simple implementation of interleave:
console.log( interleave([1,2,3,4,5,6] ,2) ); // [1,4,2,5,3,6]
console.log( interleave([1,2,3,4,5,6,7,8] ,2) ); // [1,5,2,6,3,7,4,8]
console.log( interleave([1,2,3,4,5,6] ,3) ); // [1,3,5,2,4,6]
console.log( interleave([1,2,3,4,5,6,7,8,9],3) ); // [1,4,7,2,5,8,3,6,9]
This mimics taking the array and splitting it into n equal parts, and then shifting items off the front of each partial array in sequence. (n=2 simulates a perfect halving and single shuffle of a deck of cards.)
I don't much care exactly what happens when the number of items in the array is not evenly divisible by n. Reasonable answers might either interleave the leftovers, or even "punt" and throw them all onto the end.
function interleave( deck, step ) {
var copyDeck = deck.slice(),
stop = Math.floor(copyDeck.length/step),
newDeck = [];
for (var i=0; i<step; i++) {
for (var j=0; j<stop; j++) {
newDeck[i + (j*step)] = copyDeck.shift();
}
}
if(copyDeck.length>0) {
newDeck = newDeck.concat(copyDeck);
}
return newDeck;
}
It could be done with a counter instead of shift()
function interleave( deck, step ) {
var len = deck.length,
stop = Math.floor(len/step),
newDeck = [],
cnt=0;
for (var i=0; i<step; i++) {
for (var j=0; j<stop; j++) {
newDeck[i + (j*step)] = deck[cnt++];
}
}
if(cnt<len) {
newDeck = newDeck.concat(deck.slice(cnt,len));
}
return newDeck;
}
And instead of appending the extras to the end, we can use ceil and exit when we run out
function interleave( deck, step ) {
var copyDeck = deck.slice(),
stop = Math.ceil(copyDeck.length/step),
newDeck = [];
for (var i=0; i<step; i++) {
for (var j=0; j<stop && copyDeck.length>0; j++) {
newDeck[i + (j*step)] = copyDeck.shift();
}
}
return newDeck;
}
can i has prize? :-D
function interleave(a, n) {
var i, d = a.length + 1, r = [];
for (i = 0; i < a.length; i++) {
r[i] = a[Math.floor(i * d / n % a.length)];
}
return r;
}
according to my tests r.push(... is faster than r[i] = ... so do with that as you like..
note this only works consistently with sets perfectly divisible by n, here is the most optimized version i can come up with:
function interleave(a, n) {
var i, d = (a.length + 1) / n, r = [a[0]];
for (i = 1; i < a.length; i++) {
r.push(a[Math.floor(i * d) % a.length]);
}
return r;
}
O(n-1), can anyone come up with a log version? to the mathmobile! [spinning mathman logo]
Without for loops (I've added some checkup for the equal blocks):
function interleave(arr, blocks)
{
var len = arr.length / blocks, ret = [], i = 0;
if (len % 1 != 0) return false;
while(arr.length>0)
{
ret.push(arr.splice(i, 1)[0]);
i += (len-1);
if (i>arr.length-1) {i = 0; len--;}
}
return ret;
}
alert(interleave([1,2,3,4,5,6,7,8], 2));
And playground :) http://jsfiddle.net/7tC9F/
how about functional with recursion:
function interleave(a, n) {
function f(a1, d) {
var next = a1.length && f(a1.slice(d), d);
a1.length = Math.min(a1.length, d);
return function(a2) {
if (!a1.length) {
return false;
}
a2.push(a1.shift());
if (next) {
next(a2);
}
return true;
};
}
var r = [], x = f(a, Math.ceil(a.length / n));
while (x(r)) {}
return r;
}
Phrogz was pretty close, but it didn't interleave properly. This is based on that effort:
function interleave(items, parts) {
var len = items.length;
var step = len/parts | 0;
var result = [];
for (var i=0, j; i<step; ++i) {
j = i
while (j < len) {
result.push(items[j]);
j += step;
}
}
return result;
}
interleave([0,1,2,3], 2); // 0,2,1,3
interleave([0,1,2,3,4,5,6,7,8,9,10,11], 2) // 0,6,1,7,2,8,3,9,4,10,5,11
interleave([0,1,2,3,4,5,6,7,8,9,10,11], 3) // 0,4,8,1,5,9,2,6,10,3,7,11
interleave([0,1,2,3,4,5,6,7,8,9,10,11], 4) // 0,3,6,9,1,4,7,10,2,5,8,11
interleave([0,1,2,3,4,5,6,7,8,9,10,11], 5) // 0,2,4,6,8,10,1,3,5,7,9,11
Since I've been pushed to add my own answer early (edited to fix bugs noted by RobG):
function interleave(items,parts){
var stride = Math.ceil( items.length / parts ) || 1;
var result = [], len=items.length;
for (var i=0;i<stride;++i){
for (var j=i;j<len;j+=stride){
result.push(items[j]);
}
}
return result;
}
try this one:
function interleave(deck, base){
var subdecks = [];
for(count = 0; count < base; count++){
subdecks[count] = [];
}
for(var count = 0, subdeck = 0; count < deck.length; count++){
subdecks[subdeck].push(deck[count]);
subdeck = subdeck == base - 1? 0 : subdeck + 1;
}
var newDeck = [];
for(count = 0; count < base; count++){
newDeck = newDeck.concat(subdecks[count]);
}
return newDeck;
}
I'm trying to display all the prime numbers up to 10 and it isn't working. Can you see what I did wrong?
function findPrimeNumbers() {
var count = 10,
primes = [];
for (var i = 0; i <= count; i++) {
if (count / i === 1 || count) primes.push(i);
else continue;
count -= 1;
}
for (var i = 0, len = primes.length; i < len; i++) return primes[i];
}
console.log(findPrimeNumbers());
It only returns 0 in the console.
Here's about the simplest way to generate primes. Note that there are more efficient methods, but they are harder to understand.
function findPrimeNumbers (count) {
var primes = [];
for (var J = 2; J <= count; J++) {
var possPrime = true;
for (var K = 2, factorLim = Math.sqrt (J); K <= factorLim; K++) {
if (J % K == 0) {
possPrime = false;
break;
}
}
if (possPrime)
primes.push (J);
}
return primes;
}
console.log (findPrimeNumbers (10) );
This yields all the primes <= 10:
[2, 3, 5, 7]
See Wikipedia for an explanation.
for (var i = 0, len = primes.length; i < len; i++) return primes[i];
Here you are return just the first element of the array. I think you meant something like this
var retstr = "";
for (var i = 0, len = primes.length; i < len; i++)
{
//To improve str format
if(i == len-1)
retstr += primes[i];
else
retstr += primes[i] + ", ";
}
return retstr;
Hope this helps.
if (count / i === 1 || count / i === count)
You don't say how it's not working, but the first thing that comes to my attention is that you're incrementing i, while at the same time decrementing count, so i will never get all the way to 10.
Also, count / i will cause a divide-by-zero error on the first iteration as it's written (unless Javascript magically handles that case in some way I'm not familiar with).
Then you "loop" through your return values--but you can only return once from a function, so of course you're only going to return the first value.
And you are returning from the function in the last for loop. Remove that for loop, just return the array.
function PrimeCheck(n){ //function to check prime number
for(i=2;i<n;i++){
if(n%i==0){
return false
}
}
return true;
}
function print(x){ //function to print prime numbers
var primeArray=[];
for(j=2;j<x;j++){
if(PrimeCheck(j)==true){
primeArray.push(j);
}
}
console.log(primeArray);
}
print(10); //[2,3,5,7]