CrazyEngineers
  • What is the condition for prime numbers in c++ as well as javascript?

    Updated: Oct 16, 2024
    Views: 1.0K
    what is the condition for prime numbers in c++ as well as javascript?
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Saandeep Sreerambatla

    MemberFeb 26, 2013

    Do you mean the logic?
    As far as I know the logic will be same in any programming language you do it.
    Are you sure? This action cannot be undone.
    Cancel
  • simplycoder

    MemberFeb 26, 2013

    Condition for prime would remain the same in js,c,C++... and any other language.
    Its typically same as paper-pencil logic -- If A number is divisible only by 1 and itself and has no other factors, then the number is said to be prime.


    Simplest logic would be using a for loop.

    something like this.

    boolean isPrime=true;
    for(int i=2;i<number_you_want_to_test;i++)
    {
    isPrime is true;
    if(number_you_want_to_test is divisible by i)
    {
    isPrime is false;
    the number is not prime, and break from the for loop.

    }

    }
    if(isPrime is true)
    the number is prime.

    Now you have many options to reduce the number of checks eg. instead of checking till number_you_want_to_test, you can check it number_you_want_to_test/2 think over this and why this is correct.

    After some more brain storming, you can see that this can be further reduced to checking only until square root of number_you_want_to_test with some changes.

    Brain storm more, you know that all even numbers are divisible by 2 so no even number which is greater than 2 would ever be a prime number, so think how can you avoid even numbers greater than 2. Once you do these things, you can implement advance algorithm like Sieves and such.
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register