Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

#1
May 21st, 2003, 11:45 AM
 vb.net
Demonic Swordsman DGQB

Join Date: Apr 2003
Posts: 1,043
Time spent in forums: 3 Days 23 h 3 m 53 sec
Reputation Power: 82
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
May 21st, 2003, 01:03 PM
 infamous41md
not a fan of fascism (n00b)

Join Date: Feb 2003
Location: ct
Posts: 2,756
Time spent in forums: 2 Days 11 h 4 m 29 sec
Reputation Power: 94
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
May 21st, 2003, 10:15 PM
 vb.net
Demonic Swordsman DGQB

Join Date: Apr 2003
Posts: 1,043
Time spent in forums: 3 Days 23 h 3 m 53 sec
Reputation Power: 82
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?