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

what is the condition for prime numbers in c++ as well as javascript?

Replies

  • Saandeep Sreerambatla
    Saandeep Sreerambatla
    Do you mean the logic?
    As far as I know the logic will be same in any programming language you do it.
  • simplycoder
    simplycoder
    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
    {
    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.

You are reading an archived discussion.

Related Posts

can any one help me in creating voltage sag and swell in matlab simulink for ur kind info am amateur in matlab please help me with parameters
Hi, I am new to this forum and I want to ask about networking project ideas but some limitation. Limitation are: 1. Project should be achievable within 2 month.(So that...
well i believe that there's "no tech without mech".,so a hardcore mechanical engineering fan, and wish to do something innovating & interesting with machines. Just trying to find out where...
this is muhammad nouman, i m doing B.S civil engineering from university of peshawar ,KPK province Pakistan...really looking forward to gain sm knowledge from u guys as i m new...
i need some info about color follower robot...the arena specifications....