Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. I need help with prime numbers.

I need help with prime numbers.

Scheduled Pinned Locked Moved C#
tutorialhelpquestion
12 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Alex501
    wrote on last edited by
    #1

    I have this code, but I need to find out how to make it so the program will check if its a prime number or not. For Example: If user types Number Is prime? 1 No – by definition 2 Yes – the only even prime! ? 3 Yes 4 No 5 Yes 7 Yes 17 Yes 18 No 629 ( = 17 * 37) No static void Main(string[] args) { bool current = false; int j; Console.WriteLine("Enter any number/integer"); int num = Int32.Parse(Console.ReadLine()); for (int i = 2; i <= num; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { current = true; break; } } if (current == false) Console.Write("{0} ", j); else current = false; } Console.ReadLine(); } } }

    P D G P 4 Replies Last reply
    0
    • A Alex501

      I have this code, but I need to find out how to make it so the program will check if its a prime number or not. For Example: If user types Number Is prime? 1 No – by definition 2 Yes – the only even prime! ? 3 Yes 4 No 5 Yes 7 Yes 17 Yes 18 No 629 ( = 17 * 37) No static void Main(string[] args) { bool current = false; int j; Console.WriteLine("Enter any number/integer"); int num = Int32.Parse(Console.ReadLine()); for (int i = 2; i <= num; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { current = true; break; } } if (current == false) Console.Write("{0} ", j); else current = false; } Console.ReadLine(); } } }

      P Offline
      P Offline
      Paul Conrad
      wrote on last edited by
      #2

      Where are you stuck? People won't do your homework for you.

      "I guess it's what separates the professionals from the drag and drop, girly wirly, namby pamby, wishy washy, can't code for crap types." - Pete O'Hanlon

      1 Reply Last reply
      0
      • A Alex501

        I have this code, but I need to find out how to make it so the program will check if its a prime number or not. For Example: If user types Number Is prime? 1 No – by definition 2 Yes – the only even prime! ? 3 Yes 4 No 5 Yes 7 Yes 17 Yes 18 No 629 ( = 17 * 37) No static void Main(string[] args) { bool current = false; int j; Console.WriteLine("Enter any number/integer"); int num = Int32.Parse(Console.ReadLine()); for (int i = 2; i <= num; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { current = true; break; } } if (current == false) Console.Write("{0} ", j); else current = false; } Console.ReadLine(); } } }

        D Offline
        D Offline
        DaveyM69
        wrote on last edited by
        #3

        There's something pretty screwy going on in that code. You can adapt this to suit your needs...

            static void Main(string\[\] args)
            {
                Console.Write("Enter any integer: ");
                int inputValue;
                int.TryParse(Console.ReadLine(), out inputValue);
                if (isPrimeNumber(inputValue))
                {
                    Console.WriteLine(inputValue + " is a prime number.");
                }
                else
                {
                    Console.WriteLine(inputValue + " is not a prime number.");
                }
                Console.Write("Any key to exit... ");
                Console.ReadKey();
            }
        
            public static bool isPrimeNumber(int num)
            {
                if (num < 2)
                { 
                    return false; 
                }
                for (int i = 2; i < num; i++)
                {
                    if (num % i == 0)
                    { 
                        return false; 
                    }
                }
                return true;
            }
        

        Paul... I'm not doing his homework - he was nearly there by himself (unless that was a non working example that he was given to fix)

        P L A 3 Replies Last reply
        0
        • D DaveyM69

          There's something pretty screwy going on in that code. You can adapt this to suit your needs...

              static void Main(string\[\] args)
              {
                  Console.Write("Enter any integer: ");
                  int inputValue;
                  int.TryParse(Console.ReadLine(), out inputValue);
                  if (isPrimeNumber(inputValue))
                  {
                      Console.WriteLine(inputValue + " is a prime number.");
                  }
                  else
                  {
                      Console.WriteLine(inputValue + " is not a prime number.");
                  }
                  Console.Write("Any key to exit... ");
                  Console.ReadKey();
              }
          
              public static bool isPrimeNumber(int num)
              {
                  if (num < 2)
                  { 
                      return false; 
                  }
                  for (int i = 2; i < num; i++)
                  {
                      if (num % i == 0)
                      { 
                          return false; 
                      }
                  }
                  return true;
              }
          

          Paul... I'm not doing his homework - he was nearly there by himself (unless that was a non working example that he was given to fix)

          P Offline
          P Offline
          Paul Conrad
          wrote on last edited by
          #4

          DaveyM69 wrote:

          Paul... I'm not doing his homework

          No worries. Your code looks like something the OP can work off of and get some well valued learning experience out of :-D

          "I guess it's what separates the professionals from the drag and drop, girly wirly, namby pamby, wishy washy, can't code for crap types." - Pete O'Hanlon

          1 Reply Last reply
          0
          • A Alex501

            I have this code, but I need to find out how to make it so the program will check if its a prime number or not. For Example: If user types Number Is prime? 1 No – by definition 2 Yes – the only even prime! ? 3 Yes 4 No 5 Yes 7 Yes 17 Yes 18 No 629 ( = 17 * 37) No static void Main(string[] args) { bool current = false; int j; Console.WriteLine("Enter any number/integer"); int num = Int32.Parse(Console.ReadLine()); for (int i = 2; i <= num; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { current = true; break; } } if (current == false) Console.Write("{0} ", j); else current = false; } Console.ReadLine(); } } }

            G Offline
            G Offline
            GuyThiebaut
            wrote on last edited by
            #5

            I wrote a prime class for myself some time ago - so I just dug this out of my archives. It's not the best algorithm, in terms of speed, however it works. Make sure you understand how it works because when your tutor comes to ask you how it works...

            class Prime
            {
            
                public static bool isPrime(double numIn)
                {
            
                    double testNum;
                    double testLimit;
            
                    testLimit = numIn;
                    testNum = 3;
            
                    if (0 == testLimit % 2)
                    {
                        return false;
                    }
            
                    while (testLimit > testNum)
                    {
            
                        if (0 == numIn % testNum)
                        {
                            return false;
                        }
            
                        testLimit = numIn / testNum;
                        testNum += 2;
            
                    }//while (testLimit > testNum)
            
                    return true;
            
                }//isPrime
            
            }//Prime
            
            You always pass failure on the way to success.
            L A 2 Replies Last reply
            0
            • D DaveyM69

              There's something pretty screwy going on in that code. You can adapt this to suit your needs...

                  static void Main(string\[\] args)
                  {
                      Console.Write("Enter any integer: ");
                      int inputValue;
                      int.TryParse(Console.ReadLine(), out inputValue);
                      if (isPrimeNumber(inputValue))
                      {
                          Console.WriteLine(inputValue + " is a prime number.");
                      }
                      else
                      {
                          Console.WriteLine(inputValue + " is not a prime number.");
                      }
                      Console.Write("Any key to exit... ");
                      Console.ReadKey();
                  }
              
                  public static bool isPrimeNumber(int num)
                  {
                      if (num < 2)
                      { 
                          return false; 
                      }
                      for (int i = 2; i < num; i++)
                      {
                          if (num % i == 0)
                          { 
                              return false; 
                          }
                      }
                      return true;
                  }
              

              Paul... I'm not doing his homework - he was nearly there by himself (unless that was a non working example that he was given to fix)

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #6

              yep. a major performance improvement can be obtained by replacing for (int i = 2; i < num; i++) by

              if (num==2) return true;
              for (int i = 3; i*i <= num; i+=2)

              i.e. only test odd dividers less/equal the square root of num. :)

              Luc Pattyn [Forum Guidelines] [My Articles]


              This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


              1 Reply Last reply
              0
              • G GuyThiebaut

                I wrote a prime class for myself some time ago - so I just dug this out of my archives. It's not the best algorithm, in terms of speed, however it works. Make sure you understand how it works because when your tutor comes to ask you how it works...

                class Prime
                {
                
                    public static bool isPrime(double numIn)
                    {
                
                        double testNum;
                        double testLimit;
                
                        testLimit = numIn;
                        testNum = 3;
                
                        if (0 == testLimit % 2)
                        {
                            return false;
                        }
                
                        while (testLimit > testNum)
                        {
                
                            if (0 == numIn % testNum)
                            {
                                return false;
                            }
                
                            testLimit = numIn / testNum;
                            testNum += 2;
                
                        }//while (testLimit > testNum)
                
                        return true;
                
                    }//isPrime
                
                }//Prime
                
                You always pass failure on the way to success.
                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #7

                why would you use doubles both in the API and inside the method, when the problem at hand is basically an integer one? :)

                Luc Pattyn [Forum Guidelines] [My Articles]


                This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


                G 1 Reply Last reply
                0
                • A Alex501

                  I have this code, but I need to find out how to make it so the program will check if its a prime number or not. For Example: If user types Number Is prime? 1 No – by definition 2 Yes – the only even prime! ? 3 Yes 4 No 5 Yes 7 Yes 17 Yes 18 No 629 ( = 17 * 37) No static void Main(string[] args) { bool current = false; int j; Console.WriteLine("Enter any number/integer"); int num = Int32.Parse(Console.ReadLine()); for (int i = 2; i <= num; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { current = true; break; } } if (current == false) Console.Write("{0} ", j); else current = false; } Console.ReadLine(); } } }

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #8

                  Determining whether or not each number is prime as it's entered seems inefficient. As is holding a huge Sieve that may not get fully used. So what about a more dynamic Sieve that you only extend when a new highest number is entered? Might that work?

                  L 1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    Determining whether or not each number is prime as it's entered seems inefficient. As is holding a huge Sieve that may not get fully used. So what about a more dynamic Sieve that you only extend when a new highest number is entered? Might that work?

                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #9

                    So far the linear sieve has not been mentioned nor shown in code in this thread, and it is not the way I would recommend to have a program determine primality for a specific number. The sieve methods are fine to explain the concept, and to execute by hand (i.e. for small numbers) since no divisions are required at all; successive division attempts are the normal first-order attempt in a program. For large numbers (say above 100 digits) completely different techniques are available and are getting refined all the time to investigate primality; most of them use shortcuts that reduce the computational effort tremendously at the expense of a little uncertainty (false positives for some tests, false negatives for other tests). And special libraries ("big integer" or "multiple precision" are used to operate on those numbers). :)

                    Luc Pattyn [Forum Guidelines] [My Articles]


                    This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


                    1 Reply Last reply
                    0
                    • D DaveyM69

                      There's something pretty screwy going on in that code. You can adapt this to suit your needs...

                          static void Main(string\[\] args)
                          {
                              Console.Write("Enter any integer: ");
                              int inputValue;
                              int.TryParse(Console.ReadLine(), out inputValue);
                              if (isPrimeNumber(inputValue))
                              {
                                  Console.WriteLine(inputValue + " is a prime number.");
                              }
                              else
                              {
                                  Console.WriteLine(inputValue + " is not a prime number.");
                              }
                              Console.Write("Any key to exit... ");
                              Console.ReadKey();
                          }
                      
                          public static bool isPrimeNumber(int num)
                          {
                              if (num < 2)
                              { 
                                  return false; 
                              }
                              for (int i = 2; i < num; i++)
                              {
                                  if (num % i == 0)
                                  { 
                                      return false; 
                                  }
                              }
                              return true;
                          }
                      

                      Paul... I'm not doing his homework - he was nearly there by himself (unless that was a non working example that he was given to fix)

                      A Offline
                      A Offline
                      Alex501
                      wrote on last edited by
                      #10

                      Thanks a lot. I appreciate a lot. It's not a homework, because I'm learning C# by a book and there was a problem and I could not figure out. Thanks a lot Davey.

                      1 Reply Last reply
                      0
                      • G GuyThiebaut

                        I wrote a prime class for myself some time ago - so I just dug this out of my archives. It's not the best algorithm, in terms of speed, however it works. Make sure you understand how it works because when your tutor comes to ask you how it works...

                        class Prime
                        {
                        
                            public static bool isPrime(double numIn)
                            {
                        
                                double testNum;
                                double testLimit;
                        
                                testLimit = numIn;
                                testNum = 3;
                        
                                if (0 == testLimit % 2)
                                {
                                    return false;
                                }
                        
                                while (testLimit > testNum)
                                {
                        
                                    if (0 == numIn % testNum)
                                    {
                                        return false;
                                    }
                        
                                    testLimit = numIn / testNum;
                                    testNum += 2;
                        
                                }//while (testLimit > testNum)
                        
                                return true;
                        
                            }//isPrime
                        
                        }//Prime
                        
                        You always pass failure on the way to success.
                        A Offline
                        A Offline
                        Alex501
                        wrote on last edited by
                        #11

                        Thanks a lot. It was very helpful.

                        1 Reply Last reply
                        0
                        • L Luc Pattyn

                          why would you use doubles both in the API and inside the method, when the problem at hand is basically an integer one? :)

                          Luc Pattyn [Forum Guidelines] [My Articles]


                          This month's tips: - before you ask a question here, search CodeProject, then Google; - the quality and detail of your question reflects on the effectiveness of the help you are likely to get; - use PRE tags to preserve formatting when showing multi-line code snippets.


                          G Offline
                          G Offline
                          GuyThiebaut
                          wrote on last edited by
                          #12

                          Luc Pattyn wrote:

                          why would you use doubles both in the API and inside the method, when the problem at hand is basically an integer one?

                          Possible reasons: Because it was nearing midnight when I dug out this class that I wrote as I was learning C#. My gerbils wrote the code. Not all primes have yet been discovered - I may actually discover a non whole prime. (Embarassed clearing of throat :-O )

                          You always pass failure on the way to success.
                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups