 # FreeCodeCamp -Sum All Primes- need Help

Hello, first of all i know my code is not very far from shit. I’m not satisfied now. This work nontheless

My code:

``````/*

https://primes.utm.edu/lists/small/1000.txt
*/

function falseValue( element ) {
return element == false;
};
function isFloat( n ){
return Number( n ) === n && n % 1 !== 0;
};

function sumPrimes( num ) {
let array = ;
let value = 0;

for( let k = 3; k <= num; k++ ) {
let x = 1;
let boolArray = [];

for( let d = 0; d <= k; d++ ) {
value = k / x;

if( isFloat( value ) == true  ) {
// console.log( "FLOAT "+value, x );
if( ( (x !== k)  ||  (x !== 1 ) ) ){
boolArray.push( true );
}

}else if( isFloat( value ) == false ){
// console.log( "NOT FLOAT "+value, x );
if( ( (x !== k)  &&  (x !== 1 ) ) ) {
boolArray.push( false )
}
}

x = x + 1;
}

// console.log( boolArray, k );
// console.log( "---------\n\n\n" );

if( boolArray.find( falseValue ) == undefined )  {
array.push( k );
}
}
//[2, 3, 5, 7]
//[2, 3, 5, 7, 11, 13, 17, 19]
//[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
//[...fucking too much...]
// console.log( array );

return array.reduce( (a, b) => a + b );
};

console.log( sumPrimes( 10 ) ); //17
console.log( sumPrimes( 20 ) ); //77
console.log( sumPrimes( 100 ) ); //1060
console.log( sumPrimes( 977 ) ); //73156
``````

Do you have some ideas on how i could change my code but without denaturing to much what i spend hours(yes…) to do edit: it doesn’t pass the last (977) while it’s the good result… Maybe with all my console.log in my code edit 2: yes, it was all the console.log. I commented them You need to learn to be OK with this. Not all code is going to win awards. Sometimes you’ll have to write sloppy code just to get a new feature out the door. “Get it working, fix it later”.

The first thing that stands out to me is your use of an array. All you’re looking for is a sum, so why store numbers in an array? You can also optimize your loops by thinking a bit about what a prime number is. Even numbers cannot be prime, so we know that at least ~%50 of all the numbers between 2 and num can be ignored. You can setup your loop to skip all even numbers by making two small changes. A far more involved optimization would be to look at the last digit of each number past 10. While num < 10, you have the primes 1,2,3,5,7. Past that, all prime numbers have either a 1, 3, 7, or 9 as their last digit. If you could figure out a way to check for that, you’d be able to cut out a lot of your looping. Maybe there are more of these properties that you can find.

In general, don’t worry about code being long. Shorter code isn’t necessarily better code. However, you should be worried when your code indentation starts to drift to the right. The Pyramid of Doom is very real and should be feared.

1 Like

Hi, thanks you ! If i find time, i will try to optimize/find a new way.