# Project Euler 7. Feedback request. Spoiler Alert: working solution

I ended up using some signs of divisibility instead of brute checking for division in some cases. But I am totally not sure if that was good option.

Also I have a strong feeling that logic of the last function is crappy. Somehow I am strrugling when implementing while loops.

And also, prime numbers are irritating

``````//UNIT 1
//helper function to UNIT 2
// split unit2 to maintain readability
const isDivisiblebyThree = (num) => {
return (String(num).split('').reduce((a, b) => (a + b), 0) % 3 === 0)
}

/*
testing

for (let i = 1; i <= 25; i++) {
console.log(isDivisiblebyThree(i));
}

#false false true# pattern is repeating as expected
*/

//UNIT 2
//get function isPrime(number)
//input: number, integer  output: true if prime, false otherwise

const isPrime = (num) => {
//even numbers and 1
if (num === 2) {return true;}
else if (num % 2 === 0 || num === 1) {return false;}
//deal with all numbers which are divisible by 5
//deal with 7 just cause its convinient
else if (num === 5 || num === 7) {return true;}
else if (String(num)[-1] === '5') {
return false;
}
//deal with all numbers which are divisible by 3
else if (num===3) {return true;}
else if (isDivisiblebyThree(num)) {return false;}
//starting with 11, brute iterate through divisors
//can optimize more, there are divisibity props for 7, 11....
else {
//consider looping here with step == 2
for (let i = 3; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}

}
return true;
}
}

/*
Unit testing

let testArray = [];
for (let i = 2; i <= 30; i++) {
testArray.push([i, isPrime(i)])
}
console.log(testArray)

[
[ 2, true ],   [ 3, true ],   [ 4, false ],
[ 5, true ],   [ 6, false ],  [ 7, true ],
[ 8, false ],  [ 9, false ],  [ 10, false ],
[ 11, true ],  [ 12, false ], [ 13, true ],
[ 14, false ], [ 15, false ], [ 16, false ],
[ 17, true ],  [ 18, false ], [ 19, true ],
[ 20, false ], [ 21, false ], [ 22, false ],
[ 23, true ],  [ 24, false ], [ 25, false ],
[ 26, false ], [ 27, false ], [ 28, false ],
[ 29, true ],  [ 30, false ]
]
*/

/*UNIT 3
wasn't able to use Bernard postulate or some
more complex math, consider more research/study
*/

function nthPrime(n) {
let primeCounter = 0;
let testedNumber = 1;
while (primeCounter <= n){

if (isPrime(testedNumber)) {
primeCounter++;
}

if (primeCounter == n) {
return testedNumber;
}

testedNumber++;
}
}

//fcc tests passed
``````

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.