News


Write a method that takes two parameters, both positive integers, and returns each prime number that falls on or between these two numbers. Each number printed out should be on its own line, so that if the parameters were 1 and 20, the results would be:
2
3
5
7
11
13
17
19
The method must be able to handle both parameters being the same number. It should also be able to handle the first number passed being bigger or smaller than the second. EVERYTHING must happen within this method. Your Main should only be calling the method and passing the two numbers. Any other variables you use must be declared/initialized within the method.

One implementation (40 lines of IL):

void getPrime(int one, int two)
{
int j = Math.Min(one, two);
do
{
int i = 2;
while (i < j && (j % i) != 0)
{
i++;
}
if (i == j)
Console.WriteLine(j);
} while (++j <= Math.Max(one, two));
}


Another (50+ lines of IL):

public void prime(int min, int max)
{
if (min > max) {max=i ;min = max; i = min; }
n = min;
while(n < max)
{
isprime = true;
j = 2;
while(j < n)
{

if ((n % j) == 0)
{
isprime = false;
break;
}
j++;
}
if (isprime)
{
Console.WriteLine(n);
}
n++;
}
}


Another (43 lines of IL):

private void ReturnPrimes(int inta, int intb)
{
if (inta > intb)
{
ReturnPrimes(intb, inta);
}
else
{
int i = 2;
while (i < inta)
{
if (inta % i == 0) {i = inta;}
i++;
}
if (i == inta) {Console.WriteLine(inta);}
if (inta != intb) {ReturnPrimes(inta + 1, intb);}
}
}


The winner was VB.NET (39 lines of IL):

Sub PrimeChallengeIL(ByVal low As Integer, ByVal high As Integer)
If low > high Then
PrimeChallengeIL(high, low)
Else
If Not low = high Then PrimeChallengeIL(low, high - 1)
low = 2
Do
If low = high Then Console.WriteLine(low)
If high Mod low = 0 Then Exit Do
low += 1
Loop While low <= high
End If
End Sub

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Comments

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: