Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Quick C# Query

Options
  • 30-03-2010 4:29pm
    #1
    Registered Users Posts: 1,181 ✭✭✭


    What does this line of code do?
    if ((testForPrime & 1) == 0)
    

    It's part of prime number checker but I'm not sure what this part checks
    testForPrime is a long or int


Comments

  • Closed Accounts Posts: 164 ✭✭ob




  • Registered Users Posts: 1,181 ✭✭✭ronkmonster


    The second link is where I got the algorithm from.

    Is that code just checking if the number to test is not an even number by checking bits?

    if number is odd and could be a prime, then continue with rest of checks.

    If so, is this the fastest way
    or would something like number%2!=0 be just as fast


  • Registered Users Posts: 3,287 ✭✭✭padraig_f


    if ((testForPrime & 1) == 0)
    
    Yeah he's testing if it's an even number.

    It's an optimisation, it allows him to skip even numbers in his for-loop later on:
    for (int i = 3; i <= num; [b]i += 2[/b])
    

    If so, is this the fastest way or would something like number%2!=0 be just as fast
    The answer to this is, "it's C#, who cares what's faster". You should go for the one that's more readable, so yeah number % 2 == 0 is better. If he wants to use number & 1 == 0 he should've really added a comment to say it's an even-number check. You might argue that an experienced coder should know this, but they'd usually still have to stop and ask themselves if an even-number check was the intention. Code readability is more important than minor optimisations, as poor readability makes bugs hard to find.


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    C# will probably optimize it anyways so yeah readability is better.


Advertisement