|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
how does this algorithm work?
First, please pardon my entry-level knowledge. This algorithm determines if a # is prime. I'm mainly confused on the parts involving the square root & the mod operator.
Code:
public static String isPrime(long numToCheck)
{
for (long i=2;i<=Math.sqrt(numToCheck);i++)
{
if (numToCheck%i==0)
{
return "Not prime";
}
}
return "Is indeed prime";
}
|
|
#2
|
||||
|
||||
|
basically you are just checking to see if any of the numbers smaller than or equal to the square root of your target number can be divided into your number without a remainder. The % (mod) operator returns the remainder of the division operation. So, in this exampe if our target # was 25, we would run the loop for (i = 2 -> i = 5) each iteration of the loop, we divide our target # 25 by the current value of i and check to see if there is a remainder. you can see that wen i gets to 5, the if condition will evaluate to true, since 5 % 5 == 0.
|
|
#3
|
|||
|
|||
|
I see what's going on. After 1 year of basic programming, I finally see mathematical thinking involved in a program.
![]() |
![]() |
| Viewing: Dev Shed Forums > Programming Languages - More > Software Design > how does this algorithm work? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|