Below are my functions that sum up all prime numbers that are below a given maxNum.
I don't understand why the for loop in the isPrime function doesn't work when using j <= num instead of j ** 2 <= num.
function sumPrimes(maxNum) {
let sum = 0;
for (let i = 2; i <= maxNum; i++) {
if (isPrime(i)) {
sum += i
}
}
return sum
}
function isPrime(num) {
for (let j = 2; j <= num; j++) { // when I use j ** 2 <= num it works
if (num % j === 0) {
return false
}
}
return true
}
console.log(sumPrimes(20))
if you use j <= num, the loop will count j up to the number itself and then it would match num % j === 0 and return false.
So if num was 17, the loop would be executed with 17 <= 17 which passes and the loop body executes 17 % 17 === 0 so it always returns false, no matter what number you pass in.
you could use j < num instead of j <= num in the loop head which should also work because the number itself is never reached when using the smaller than sign.
Related
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))
I am trying to implement Euler's Totient Function (phi) in Javascript. So far this is what I have:
function phi(n) {
var result = n;
for (let i=2; i*i<=n; i++) {
if (n % i === 0) {
while (n % i === 0) {
n /= i;
result -= result / i;
}
}
}
if (n > 1) {
result -= result / n;
}
return result;
}
Unfortunately it all goes wrong when it comes up to multiples of 4. How do I improve this?
Inspired by https://www.geeksforgeeks.org/eulers-totient-function/
function phi(n) {
// return Greater Common Denominator of two given numbers
function gcd(a, b) {
if (a === 0) {
return b;
}
return gcd(b % a, a);
}
// init
var result = 1;
// walk through all integers up to n
for (let i = 2; i < n; i++) {
if (gcd(i, n) === 1) {
result++;
}
}
return result;
}
You should implement result = 1, then result ++ whenever you encounter a number coprime to the number you input. For that, you have to find the gcd function and that can be done with various methods, such as ArrayLists (like in Java) or with recursive functions.
Not the most eficient way, but rather straightforward:
function phi(n) {
let divArr = []; // this is an array for the common divisors of our n
let primeCount = 0; // this is a counter of divisors
for (let i = 0; i <= n - 1; i++) {
if (n % i === 0) {
divArr.push(i);
}
}
for (let j = n - 1; j > 0; j--) { //j is all potential coprimes
for (let k = divArr.length - 1; k >= 0; k--) { //we get the indeces of the divArr and thus we can loop through all the potentail divisors
//here we check if our potential coprimes are comprimes or not
//run possible coprimes through the list of divisors
if (j % divArr[k] === 0 && divArr[k] !== 1) { //if a potential coprime can be divided by any element of the array of n's divisors we break the arra's loop i. e. k and go the j++
break
} else if (j % divArr[k] !== 0) { //if a potential coprime j cannot be divided by any element of divArray then it's ok and we simply stick to the next k and waiting for 2 possible cases: either it will reach 1 and we primeCount++ or eventually be divided and then we break the loop
continue
} else if (divArr[k] === 1) { //if can be divided without a remainder, greatest common divisor is not zero so we should break the loop
primeCount++;
}
}
}
console.log(divArr, primeCount)
}
function primeSieve() {
for(i = 0; i <= 100; i++){
let flag = true
for(let j = 2; j < i/2; j++){
if(i % j === 0){
flag = false
}
}
if(flag){
console.log(i)
}
}
}
primeSieve();
Hi,
I'm studying some algos and ran into a prime sieve problem. I'm trying to print all prime numbers between 0 and 100 and it's working for the most part. However, i realized that 4 slipped in somehow and i can't figure out why for the life of me. Wondering if i can get a few pairs of eyes and see how 4 ended up being logged to the console and why that's the case.
thank you!
Your condition in the inner loop:
for (let j = 2; j < i / 2; j++) {
is
j < i / 2
This means that when i is 4, once j gets to 2 (or, since j is always initialized to 2, before the first iteration), the loop breaks. So, without any iterations, there's never any chance for an i of 4 to get to flag = false.
Change to
for (let j = 2; j <= i / 2; j++) {
Also, per wikipedia:
A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers.
So you should probably start i at 2, not 0.
Also, just like your let j, it would be good to declare i with let as well so as not to implicitly pollute the global scope:
function primeSieve() {
for (let i = 2; i <= 100; i++) {
let flag = true
for (let j = 2; j <= i / 2; j++) {
if (i % j === 0) {
flag = false
}
}
if (flag) {
console.log(i)
}
}
}
primeSieve();
Beside the including the value for j to check with j <= i / 2, you could omit the use of a flag and use continue with a label for the outer loop.
function primeSieve() {
outer: for (var i = 2; i <= 100; i++) {
for (var j = 2; j <= i / 2; j++) {
if (i % j === 0) {
continue outer;
}
}
console.log(i);
}
}
primeSieve();
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) {