Created
November 8, 2016 16:52
-
-
Save kristynrb/3589a9874919d2997cb77f4a65d1c121 to your computer and use it in GitHub Desktop.
w02d03_morning_exercise_solution_prime_numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//////////////////////////////////////////////// | |
//Part One | |
/////////////////////////////////////////////// | |
var isPrime = function(num) { | |
// Prime is any number greater than 1. | |
if (num < 2) { return false }; | |
//First section, see if the number entered is evenly divisible by any number (other than 1). | |
//Second section, as per the instructions, you only need to test up to the square root of the number. | |
//third is just increasing the number that is checked each time. | |
for (var i=2; i <= Math.sqrt(num); i++) { | |
if (num % i === 0) { | |
return false; | |
} | |
} | |
return true; | |
} | |
console.log(isPrime(11)); | |
/////////////////////////////////////////////// | |
//Part Two | |
/////////////////////////////////////////////// | |
var printPrimes = function(limit) { | |
//first section represents the number that will go through the `isPrime` function. | |
//second section sets the limit - check for prime numbers only up to this number. | |
//third is just increasing the number that is checked each time. | |
for (var i=1; i <= limit; i++) { | |
if (isPrime(i)) { | |
//if the number is a prime, the `isPrime` function returns `true` and this triggers the console.log. | |
console.log(i); | |
} | |
} | |
} | |
console.log(printPrimes(97)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment