How to Identify Prime Numbers Using Eratosthenes in C#?

In summary, the programmer is having trouble printing out the list of 1000 numbers. The code might be improved by replacing the for loops with a List<int> variable and then printing out the list using the ToString() method.
  • #1
SGJ
10
0
Mod note: added code tags
C:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{

  class Program
  {
    static void Main(string[] args)
    {
       List<int> number = new List<int>(1000); // int list for 1000 numbers
       for(int i = 0; i < 1000; i++) // for loop that populates the numbers array
       {
          number.Add (i + 1); // the first position in the array will equal 1 rather than zero
       }
       for (int i = 2; i <= 32; i++) // This is the first loop that will run the square root of 1000 times
       {  
          for (int j = 2; j < 32; j++) // Nested for loop that will run for the square root of 1000 times
          {
               number.Remove(j * i); // every muptiple will be removed leaving only odd numbers
          }
        
          foreach (int numbers in number)
          {
             Console.Write(" " + number.Count); // writes the numbers still left in the list
          }
        
      }
      Console.ReadKey(); // Keeps program open
    }
  }
}
 
Last edited by a moderator:
Technology news on Phys.org
  • #2
So here is my problem (this is my first time using lists and this site so bear with me) whenever I try to run this it prints 970 and will repeat that number hundreds of times. I want it to print 1, 3, 5, 7, 11, 13, 17... ect. Please help urgent C#.
 
  • #3
number.Count should return the number of items in the list. So you are printing '970' ... 970 times!

Try Console.Write(" " + numbers) instead.
 
  • #4
jack action said:
number.Count should return the number of items in the list. So you are printing '970' ... 970 times!

Try Console.Write(" " + numbers) instead.
I tried that and it printed 1-1000 several hundred times.
I then tried just printing "number" but it printed "systems collection generic" another thousand or so times.
 
  • #5
I'm not really good with C#, but this is a good resource where I found the following:

Code:
number.ForEach(Print);

private static void Print(string s)
{
    Console.Write(" " + s);
}

There is also a simple method:

Code:
Console.Write(number.ToString());
 
  • #6
My very first observation (being a C# programmer) is that, since you've included System.LINQ, you might want to consider fully using it by changing

Code:
       List<int> number = new List<int>(1000); // int list for 1000 numbers
       for(int i = 0; i < 1000; i++) // for loop that populates the numbers array
       {
          number.Add (i + 1); // the first position in the array will equal 1 rather than zero
       }

to

Code:
List<int> number = Enumerable.Range(1,1000).ToList();
 
  • #7
SlurrerOfSpeech said:
My very first observation (being a C# programmer) is that, since you've included System.LINQ, you might want to consider fully using it by changing

Code:
       List<int> number = new List<int>(1000); // int list for 1000 numbers
       for(int i = 0; i < 1000; i++) // for loop that populates the numbers array
       {
          number.Add (i + 1); // the first position in the array will equal 1 rather than zero
       }

to

Code:
List<int> number = Enumerable.Range(1,1000).ToList();
Thank you for that!
Do you have any solution as to why I am getting large repetitions of numbers starting at around 970?
 
  • #8
SGJ said:
I want it to print 1, 3, 5, 7, 11, 13, 17... ect. Please help urgent C#.

The error lies in your for loops. Take a careful look again. As a hint, don't print out numbers until you have removed what you need first.
 
  • #9
SGJ said:
Thank you for that!
Do you have any solution as to why I am getting large repetitions of numbers starting at around 970?
Your algorithm is incorrect. After removing values from your list that are the products of numbers of the form a * b, where both a and b are in {2..32}, your list ends up with numbers that aren't prime. The first one I see starts at 74 (= 2 * 37). Also present are is and b = 82, 86, 94, 106, and a slew of others. Instead of removing numbers a * b with a and b in {2, ..., 32}, go through the entire list and remove multiples of 2, then multiples of 3, and so on, up to 32.
 
  • Like
Likes QuantumQuest
  • #10
BTW, your foreach loop is nested within the outer for loop, which causes it to run 31 times (printing out your list that number of times). It should NOT be nested within that outer for loop.

C:
static void Main(string[] args)
{
     List<int> number = new List<int>(1000); // int list for 1000 numbers
     for(int i = 0; i < 1000; i++) // for loop that populates the numbers array
     {
         number.Add (i + 1); // the first position in the array will equal 1 rather than zero
     }
     for (int i = 2; i <= 32; i++) // This is the first loop that will run the square root of 1000 times
     { 
        for (int j = 2; j < 32; j++) // Nested for loop that will run for the square root of 1000 times
        {
            number.Remove(j * i); // every muptiple will be removed leaving only odd numbers
        }
     } // <---- Added by Mark44
        
    foreach (int numbers in number)
    {
       Console.Write(" " + number[numbers]); // writes the numbers still left in the list
    }
        
    Console.ReadKey(); // Keeps program open
}
 
  • #11
Also, as Mark44 points out your algorithm is incorrect. You will see it if you first correct the error according to my hint: the resulting numbers are not all primes.
 
  • #12
QuantumQuest said:
Also, as Mark44 points out your algorithm is incorrect. You will see it if you first correct the error according to my hint: the resulting numbers are not all primes.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1{

class Program{

static void Main(string[] args){

List<int> number = new List<int>(1000); // int list for 1000 numbersfor (int i = 0; i < 1000; i++) // for loop that populates the numbers array{

number.Add(i + 1); // the first position in the array will equal 1 rather than zero}
for (int i = 2; i < 1000; i++) // This is the first loop that will run the square root of 1000 times{

for (int j = 2; j < 1000; j++) // Nested for loop that will run for the square root of 1000 times{

if (i * j < 1000){

number.Remove(j * i); // every muptiple will be removed leaving only odd numbers}}

}

foreach (int numbers in number){

Console.Write(" " + number[numbers]); // writes the numbers still left in the list}
So this is as far as I got. Thanks to your help, the multiples stopped and i do have some primes but some of them are missing such as 13, all the primes in the 20's etc. The (" " + number[numbers]) line gives it a Out of range error.
 
  • #13
SGJ said:
So this is as far as I got. Thanks to your help, the multiples stopped and i do have some primes but some of them are missing such as 13, all the primes in the 20's etc. The (" " + number[numbers]) line gives it a Out of range error.

I'll give a hint in a different direction. Try to fill your array with all multiples of 2 and 3. To do this, you need two nested loops, the first going from 2 to 1000 and the second might begin with the double of the variable in the first loop, but the tricky part is how to increment it in order to fill all the multiples. I leave it to you to tinker with it, till you figure it out. Then, you can print out whatever is not included in your array, using another loop. What will be these numbers you will print out?
 
  • #14
SGJ said:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1<snip>
@SGJ, please use code tags when you post code. Not doing so loses any indentation you have.

[code=c]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
// etc. [/code]
 
  • #15
C:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication1{

class Program

 
{

static void Main(string[] args){

List<int> number = new List<int>(1000); // int list for 1000 numbersfor (int i = 0; i < 1000; i++) // for loop that populates the numbers array{

number.Add(i + 1); // the first position in the array will equal 1 rather than zero}
for (int i = 2; i < 1000; i++) // This is the first loop that will run the square root of 1000 times{

for (int j = 2; j < 1000; j++) // Nested for loop that will run for the square root of 1000 times{

if (i * j < 1000){

number.Remove(j * i); // every muptiple will be removed leaving only odd numbers}}

}

foreach (int numbers in number){

Console.Write(" " + number[numbers]); // writes the numbers still left in the list}
 
// etc.
 
  • #16
Mark44 said:
@SGJ, please use code tags when you post code. Not doing so loses any indentation you have.

[code=c]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
// etc. [/code]
sorry I am new to this, I posted the code in the comment above.
 
  • #17
Do you have a question about what you posted in #14?
 
  • #18
Mark44 said:
Do you have a question about what you posted in #14?

yes, why do I get a range error at Console.WriteLine(" " + number[numbers])
 
  • #19
C:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
  class Program 
  {

    static void Main(string[] args)
    {
       List<int> number = new List<int>(1000); // int list for 1000 numbers
       int[] check = new int[1000]; // another array for the mathematics.
       // for (int i = 0; i < 1000; i++) // for loop that populates the numbers array
       // {
          // number.Add(i + 1); // the first position in the array will equal 1 rather than zero
       // }

       for (int i = 0; i < 1000; i++) // This is the first loop that will run the square root of 1000 times
       {
          for (int j = 2; j < 1000; j++) // Nested for loop that will run for the square root of 1000 times
         {
            check[j] = i + 1; // populates check
            if(check[ i ] % check[j] == 1) // If the remainder of check position i and check position j is one (odd number test)
           {
              number.Add(i); // The number is added to number
           }
        }
     }
  
     foreach (int numbers in number)
     {
        Console.Write(" " + number.Count); // writes the numbers still left in the list
     }
so I decided to take a completely different route. Now I get a domain/range error at the line (check[ i] % check[j] ==1)

I ONLY USED 1 AS A TEST.
 
Last edited by a moderator:
  • #20
I'm still looking at your code, but in the meantime, a couple of tips:
1. Don't put any spaces in the starting code tag. It has to be [code=c], not [code = c]. The extra spaces breaks things.
2. An array index of i (as in check[i]) is treated as a starting Italic tag, and you end up garbled code, as the browser "eats up" Italics tags, bold tags, etc. The workaround is to add a space before the i, as in check[ i].
 
  • #21
SGJ said:
C:
        for (int j = 2; j < 1000; j++) // Nested for loop that will run for the square root of 1000 times
         {
            check[j] = i + 1; // populates check
            if(check[ i ] % check[j] == 1) // If the remainder of check position i and check position j is one (odd number test)
so I decided to take a completely different route.
What are you even trying to do? I can't quite see where are you going with this. Try using some real comments, not repeating something everyone can see. E.g. replace "This loop runs 1000 times" with "this array holds...whatever".

The contents of the "check" array are always check[j]=i+1. Why do you need such an array?
SGJ said:
C:
        Console.Write(" " + number.Count); // writes the numbers still left in the list
Haven't we fixed this already?

You should only ask if you are desperate and can't find an error. Posting the first, half baked attempt here is not going to teach you anything.
 
  • #22
SGJ said:
yes, why do I get a range error at Console.WriteLine(" " + number[numbers])
Because numbers is too large to be a valid index for your number list.

I would also recommend giving your variables better names. numbers is OK for the list, but IMO list would be better. On the other hand, number is so close to numbers lexicographically that it would be easy for someone (including yourself) to get confused about which one does what.

Since your code is C++, you are presumably using Visual Studio, which has a very nice debugger. Use it to find the values of your variables when your code is running.

SGJ said:
Now I get a domain/range error at the line (check[ i] % check[j] ==1)
Same reason as above. When you get the range error, check the values of i and j.

Also, as already mentioned, there really is no need for the check list.
 

Related to How to Identify Prime Numbers Using Eratosthenes in C#?

1. What are prime numbers?

Prime numbers are positive integers that are divisible only by 1 and themselves. In other words, they have no other factors besides 1 and themselves.

2. Who was Eratosthenes?

Eratosthenes was an ancient Greek mathematician who developed a method for finding prime numbers known as the Sieve of Eratosthenes.

3. How does the Sieve of Eratosthenes work?

The Sieve of Eratosthenes is a method for finding all prime numbers up to a given number. It works by crossing out all multiples of a number starting from 2, until all non-prime numbers are eliminated and the remaining numbers are prime.

4. What is the significance of prime numbers?

Prime numbers have many important applications in mathematics and computer science. They are used in cryptography, coding theory, and prime factorization, among other areas. They also have a deep connection to the distribution of whole numbers.

5. Are there any known patterns in prime numbers?

While there are some patterns that have been observed in prime numbers, such as the distribution of prime gaps, the overall distribution of prime numbers is still largely unpredictable. This is one of the main reasons why prime numbers are so fascinating to mathematicians and scientists.

Similar threads

  • Programming and Computer Science
Replies
14
Views
2K
  • Programming and Computer Science
Replies
1
Views
975
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
4
Views
4K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
2
Views
831
  • Programming and Computer Science
2
Replies
47
Views
4K
  • Programming and Computer Science
Replies
3
Views
910
  • Programming and Computer Science
Replies
4
Views
10K
Back
Top