-2

I am learning C# and I struggle with a task.
I try to write a program which asks for a range of numbers, and return all the prime numbers.

However I always get the error:

Not all code paths return a value

First I made a function to check if a given number is a prime number, and it seems to work, here is the code:

public bool IsPrime(int theNumber)
{
    for(int i = 2; i <= (theNumber/2)+1; i++)
    {
        if(theNumber%i == 0)
        {
            return false;
        }
    }

    return true;

Now I want to loop it in a for loop, and return all the prime numbers in that range... But it doesn't work.

Seems like the problem is that I am missing a return statement in case the if boolean is false. But obviously I don't want a return if my first method isPrime(int theNumber) returns a false.

This is the code I have:

public int AllPrimesInRange(int lowerEdge, int upperEdge)
{
    for(int i = lowerEdge; i <= upperEdge; i++)
    {
        if (IsPrime(i))
        {
            return i;
        }              
    }

I hope someone can help me.. Thank you in advance.

GSerg
  • 76,472
  • 17
  • 159
  • 346
  • 1
    You realise that your `AllPrimesInRange` function, if it worked, could only possibly return one number, not several? And that it would still need to return something in case there are no prime numbers between `lowerEdge` and `upperEdge`? It would appear you wanted an [iterator function](https://learn.microsoft.com/en-us/dotnet/csharp/iterators#enumeration-sources-with-iterator-methods). – GSerg Apr 03 '23 at 13:37
  • Oh thank you for the super fast help. Okay i think i take a step back and think about this again. – Angelos Makrygiannis Apr 03 '23 at 13:41
  • you should look into prime sieve. you really only need to check the factors up to the SQRT of a number to see if its prime – johnny 5 Apr 03 '23 at 13:49

1 Answers1

0

It seems that you want a IEnumerable<int>:

Idealy I would like it to return nothing if there is no prime number

Let's implement it:

public IEnumerable<int> AllPrimesInRange(int lowerEdge, int upperEdge) {
  lowerEdge = Math.Max(lowerEdge, 2);

  // Special Case - 2 - the only even prime
  if (lowerEdge == 2 && upperEdge >= lowerEdge)
    yield return 2; 

  // Nearest odd int (2 -> 3, 146 -> 147 etc.)
  lowerEdge = (lowerEdge / 2 * 2 + 1); 

  for (int number = lowerEdge; number <= upperEdge; number += 2) 
    if (IsPrime(number))
      yield return number;
}

Usage

foreach (int number in AllPrimesInRange(35, 145)) {
  Console.WriteLine(number);  
}

Note, that unlike return it's quite possible that the method returns nothing, i.e. yield return is never executed.

Fiddle

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215