-3

I'm working on a Euler problem and am trying to build a function that checks a number to see if its a prime. I get error messages about the line:

if (a)%(b)==0{

Is my syntax wrong or is it impossible to use % on a variable rather on an integer?

var x = Math.sqrt(600851475143);
var y = Math.round(x);
y++;
console.log(y);

//find all of the prime numbers up to the square root number.  Put them in an array.  
//Check each ascending number against the prime numbers in the array to see if %=0

var primes = [2,3];
var a =(3);

while (a<y){
    a++;
    isPrime(a)
}
function isPrime(arr){
for (var i = 0; i < arr.length; i++){
    var b = primes[i];
    //next line is a problem
    if (a)%(b)==0{
        break
    }else{
        primes.push(a);
        }
    }
}
jasonp49
  • 1
  • 1
  • 2
    Yes your syntax is wrong. It’s `if(a % b == 0){`…`}`. This doesn’t have anything to do with the modulus operator, but with your `if` statement. – Sebastian Simon Jun 16 '16 at 03:06
  • 1
    If you lack the skill to see the trivial error with your brackets then you are nowhere near having enough skill to be able to attempt a Euler problem. Go back and work on simpler things. – JK. Jun 16 '16 at 03:18
  • @JK Having problems with the syntax of a new language doesn't mean one lacks the understanding of a mathematician. Instead, the OP should try better tooling (devtools, IDE, linter) that points out syntax errors. – Bergi Jun 16 '16 at 03:31

2 Answers2

1

You can always use operations on variables. When the script is run, the variables are substituted with the real values associated with the variables.

var a = 3,
    b = 5;
if(a%b == 0) {}

Is equal to

if(3%5 == 0) {}

You just used the wrong syntax in your statement:

if (a)%(b)==0 {}

It should be:

if(a%b == 0) {}

In JavaScript, you need to wrap your if statement with squiggly brackets, not the variables. Your code would trigger a syntax error because the if statement is written incorrectly and it doesn't expect a random modulus, equal signs and other symbols outside the parentheses.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
0

Yes you can use it

But the issue is here in if loop

if (a)%(b)==0{ // Here it is assuming the the condition statement ends with )

which is after a

In reality it will be

if ((a)%(b)==0){  // Note braces pointed by ^^
   ^          ^       
      break
    }else{
        primes.push(a);
        }
    }
}
brk
  • 48,835
  • 10
  • 56
  • 78