Skip to content

Instantly share code, notes, and snippets.

@dasider41
Created September 16, 2019 21:09
Show Gist options
  • Save dasider41/72373497d350097a1ffeb1605196a8d9 to your computer and use it in GitHub Desktop.
Save dasider41/72373497d350097a1ffeb1605196a8d9 to your computer and use it in GitHub Desktop.
/*
Count Primes
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
*/
/**
* @param {number} n
* @return {number}
*/
var countPrimes = function(n) {
const isPrime = n => {
for (j = 2; j <= Math.sqrt(n); j++) {
if (n % j === 0) {
return false;
}
}
return n > 1;
};
let primesCount = 0;
for (i = 2; i < n; i++) {
if (isPrime(i)) {
primesCount++;
}
}
return primesCount;
};
console.log(countPrimes(499979));
@dasider41
Copy link
Author

get total for prime numbers

<?php

function isPrime(int $n): bool
{
    if ($n < 2) {
        return false;
    }

    for ($j = 2; $j < $n; $j++) {
        if ($n % $j === 0) {
            return false;
        }
    }

    return true;
}

$sum = 0;
for ($i = 2; $i <= 100; $i++) {
    if (isPrime($i)) {
        $sum += $i;
    }
}

echo $sum;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment