Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

prime numbers using for loop in Js

// range = 1 o 20 
for(let number=2 ; number<=20; number++){
    let isPrime = true;

for (let i=2; i<= number-1;i++){
    if(number%i===0){
        isPrime = false;
        break
    }
}
if (isPrime) console.log(number);
}
// result = 2,3,5,7,11,13,17,19
Comment

prime number in javascript using for loop

function sumPrimes(num) {
  // Check all numbers for primality
  let primes = [];
  for (let i = 2; i <= num; i++) {
    if (primes.every((prime) => i % prime !== 0))
      primes.push(i);
  }
  return primes.reduce((sum, prime) => sum + prime, 0);
}
Comment

prime number in javascript using for loop

function sumPrimes(num) {
  // Helper function to check primality
  function isPrime(num) {
    for (let i = 2; i <= Math.sqrt(num); i++) {
      if (num % i == 0)
        return false;
    }
    return true;
  }

  // Check all numbers for primality
  let sum = 0;
  for (let i = 2; i <= num; i++) {
    if (isPrime(i))
      sum += i;
  }
  return sum;
}
Comment

prime number in javascript using for loop

function sumPrimes(num) {
  // Prime number sieve
  let isPrime = Array(num + 1).fill(true);
  // 0 and 1 are not prime
  isPrime[0] = false;
  isPrime[1] = false;
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (isPrime[i]) {
      // i has not been marked false -- it is prime
      for (let j = i * i; j <= num; j += i)
        isPrime[j] = false;
    }
  }

  // Sum all values still marked prime
  return isPrime.reduce(
    (sum, prime, index) => prime ? sum + index : sum, 0
  );
}
Comment

PREVIOUS NEXT
Code Example
Javascript :: symbol in keyword for arrow below 
Javascript :: npm function-memoizer 
Javascript :: javascript döngü dizisi 
Javascript :: get biggest element in array javascript 
Javascript :: change xy scale phaser 
Javascript :: Disemvowel Trolls 
Javascript :: phaser place on line 
Javascript :: phaser spread 
Javascript :: phaser generate frame names 
Javascript :: phaser stagger play 1 
Javascript :: mui adding eye toggle at password field 
Javascript :: on refresh action set position rainmeter 
Javascript :: chai promise resolved 
Javascript :: nodejs stream pipeline with custom transform 
Javascript :: get product 
Javascript :: moment js with nodejs 
Javascript :: convert javascript to python 
Javascript :: javascript map foreach 
Javascript :: select and select based on value in jquery 
Javascript :: add google map in react js 
Javascript :: nextjs app 
Javascript :: react check if browser is in dark mode 
Javascript :: javascript self executing function 
Javascript :: export default class react 
Javascript :: unicode in javascript 
Javascript :: preview file before upload in react 
Javascript :: javascrip functions parameters 
Javascript :: alertify js examples 
Javascript :: mdn react 
Javascript :: graphql json schema 
ADD CONTENT
Topic
Content
Source link
Name
9+7 =