-2

I have a problem with my code and i don't know how to solve it. Basically this program prints prime numbers based on the user input and at the end it prints their sum. This works perfectly until a certain amount, example: if i input 10, it shows ten correct prime numbers, but if i input 100, it also prints a number that is not prime, in this case 533. I don't know where i'm wrong.

Thanks for the support.

EDIT: I solved it on my own. Basically there was an error in the first "If" inside the for loop, i've simply added "c = n - 1;" after n++. Now it works perfectly.

Console.Write("How many prime numbers?: ");
int l = Convert.ToInt32(Console.ReadLine());
int n = 2;
int sum = 0;
sum += n;
Console.WriteLine(n);
n++;
int i = 1;
l++;
while (i < l)
{
    for (int c = n - 1; c > 1; c--)
    {
        if (n % c == 0)
        {
            n++;
        }
        else if (n % c != 0 && c == 2)
        {
            sum += n;
            Console.WriteLine(n);
            n++;
            i++;
        }
    }
}
Console.WriteLine("Sum: " + sum);
  • 3
    The code looks wrong. Normally you'd check each number for all reasonable divisors. The code shown instead tries to be super smart by moving to next number after checking through half of the divisors... Code is already made very hacky and hard to read by using single letter identifiers and backward counting loop... so there is really no need for that strange shift to next number. Duplicate shows same code written in more readable manner (as well as adding correct optimization to cut down number of check). If that information is not enough [edit] question with details that are unclear. – Alexei Levenkov Jan 27 '21 at 00:52
  • I solved it on my own by adding a simple "c = n + 1;" after n++ in the first "If", now it works perfectly. I sincerely find my code easy to understand (yes maybe the next time i will change the name of the variables ahahah). Anyway my program works this way: it starts from the number 2, then there are two loops, the first is the while with "i < l" (i increments every time a prime number is printed) and the for loop inside checks all the remainders for all the numbers from n - 1 to 2. If the remainder is equal to 0, for loop again, else it prints the number and "i", "n", "sum" are incremented. – Pietro Ceriani Jan 27 '21 at 01:51

1 Answers1

0

Let's start from extracting method:

public static bool IsPrime(int value) {
  if (value <= 1)
    return false;
  if (value % 2 == 0)
    retutn value == 2;

  int n = (int) (Math.Sqrt(value) + 0.5);

  for (int d = 3; d <= n; d += 2)
    if (value % d == 0)
      return false;

  return true;
}

Having this method implemented you can easily compute the sum of the first N primes:

  int N = 100;
  long s = 0;

  for (int p = 1; N > 0; ++p) {
    if (IsPrime(p)) {
      s += p;
      N -= 1;
    }
  }

  Console.Write(s);
  

Another (a bit more complex) possibility is prime numbers enumeration:

  public static IEnumerable<long> Primes() {
    yield return 2;

    List<int> knownPrimes = new List<int>();

    for (int p = 3; ; p += 2) {
      int n = (int) (Math.Sqrt(p) = 0.5);

      bool isPrime = true;

      foreach (int d in knownPrimes) {
        if (d > n)
          break;
        if (p % n == 0) {
          isPrime = false;

          break; 
        } 
      } 

      if (isPrime) {
        knownPrimes.Add(p);

        yield return p; 
      }
    }
  }

Then you can query enumeration with a help of Linq:

  using System.Linq;

  ...

  long s = Primes()
    .Take(N)
    .Sum();  
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Thanks for your reply, anyway i solved it on my own. Basically there was an error in the first "If" inside the for loop, i've simply added "c = n - 1;" after n++. Now it works perfectly. – Pietro Ceriani Jan 27 '21 at 01:38