Replies
Welcome, guest
Join CrazyEngineers to reply, ask questions, and participate in conversations.
CrazyEngineers powered by Jatra Community Platform
-
@saandeep-sreerambatla-hWHU1M • Feb 26, 2013
Do you mean the logic?
As far as I know the logic will be same in any programming language you do it. -
@simplycoder-NsBEdD • Feb 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.