Help with Perfect Numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hipfunkyjive
    New Member
    • Sep 2008
    • 1

    Help with Perfect Numbers

    Basically my program has to find perfect numbers in a range 1- 1000

    it works , kinda but it displays a few numbers that are not perfect for example the first Perfect numbers are : 6 28 496

    my program displays : 6 24 28 496

    here is my code:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Ch04Exercise09
    {
        public class Perfect
        {
            public static void Main(string[] args)
            {
                int number, test, total;
    
                for (number = 1; number <= 1000; ++number)
                {
                    
                    for (test = 1, total = 0; test < number; ++test)
                    {
    
                        if (number % test == 0)
                        {
                            total += test;
    
                            if (total == number)
                                Console.WriteLine("{0}", number);
                        }
                        
                    }
                    
                }
            }
        }
    }
    What did I do wrong?
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Hmm I'm not sure what you're doing in there, but i just wrote some quick code and got these numbers in the first 1000:
    6
    28
    496

    I think its because you check your totals inside the inner for loop, instead of on the outside?

    Comment

    • mldisibio
      Recognized Expert New Member
      • Sep 2008
      • 191

      #3
      Many forums will often post the caveat: we are not here to do your homework for you!

      You need to find the problem yourself. However, here is a way to print out the debuging info you need to analize. The problem should then become pretty obvious. Good Luck! :

      Code:
      using System;
      using System.Collections.Generic;
      using System.Text;
      namespace Ch04Exercise09 {
        public class Perfect {
      
          public static void Main(string[] args) {
            int number, test, total;
      
            for (number = 1; number <= 30; ++number) {
              Console.WriteLine();
              Console.WriteLine("Testing: {0:D2}:", number);
              for (test = 1, total = 0; test < number; ++test) {
                if (number % test == 0) {
                  total += test;
                  Console.WriteLine("Divisor: {0:D2} RunningTotal: {1:D3}", test, total);
                  if (total == number)
                    Console.WriteLine("{0, 48}{1}", "total == number = ", number);
                }
              }
            }
          }
      
        }
      }

      Comment

      • balabaster
        Recognized Expert Contributor
        • Mar 2007
        • 798

        #4
        I had to write something like this a while back...

        Prime numbers are all odd and you don't need to search all of them...given that by definition 0, 1 and 2 are prime numbers, you can assume these.

        Also, all numbers are divisible by their square roots...so we don't need to check on any divisors higher than the square root.

        Mod returns the remainder of a numerator divided by a denominator. Given that we know that all primes are odd, it is a given that all numbers where the mod of 2 is 0 are even numbers are not prime... given that if a number is divisible by an even number, it is also divisible 2, prime numbers are only divisible by odd numbers, so we don't even need to check those...

        So:

        VB
        Code:
        Function IsPrime(ByVal Value As Integer) As Boolean
        
          If (Value >= 0) And (Value <= 3) Then Return True 'These are automatically prime
          If Value Mod 2 = 0 Then Return False 'These are automatically not prime
        
          For CrntCheck = 3 To Math.SqRt(Value) Step 2
            If Value Mod CrntCheck = 0 Then Return False
          Next
        
          'We didn't find any numbers by which this value is divisible, which means
          'it is prime...
          Return True
        
        End Function
        C#
        Code:
        function isPrime(integer Value)
        {
          if ((value >= 0) && (value <= 3)) return true;
          if (value % 2 == 0) return false;
          for (int crntCheck = 3; crntCheck < Math.Sqrt(Value); i = i + 2)
          {
            if (value % crntCheck == 0) return false
          }
          return true;
        }

        Comment

        • mldisibio
          Recognized Expert New Member
          • Sep 2008
          • 191

          #5
          That's a great algorithm, but I think his homework was to write an algorithm to find the pefect numbers between 1 and 1000.

          According to Wikipedia: a perfect number is defined as a positive integer which is the sum of its proper positive divisors, that is, the sum of the positive divisors excluding the number itself.

          I wan't aware of the definition myself either. There's some interesting reading there if you are a math fan, including Euclid's formula to find the same:
          Perfect Numbers - Wikipedia

          Comment

          • balabaster
            Recognized Expert Contributor
            • Mar 2007
            • 798

            #6
            Originally posted by mldisibio
            That's a great algorithm, but I think his homework was to write an algorithm to find the pefect numbers between 1 and 1000.

            According to Wikipedia: a perfect number is defined as a positive integer which is the sum of its proper positive divisors, that is, the sum of the positive divisors excluding the number itself.

            I wan't aware of the definition myself either. There's some interesting reading there if you are a math fan, including Euclid's formula to find the same:
            Perfect Numbers - Wikipedia
            Oops, I don't know why I read that as a prime number... :oP Oh well, maybe this will be useful for other homework, hehe.

            Comment

            • Curtis Rutland
              Recognized Expert Specialist
              • Apr 2008
              • 3264

              #7
              Originally posted by mldisibio
              Many forums will often post the caveat: we are not here to do your homework for you!
              And our forum is most definitely one of those!

              But since the OP wasn't asking for a solution, just some help, we can allow it.

              But the OP shouldn't his/her entire code. Professors have been known to browse this site, they wouldn't look to kindly to see exactly what you turned in out there on the internet. The intentions might be misunderstood as cheating.

              Comment

              • balabaster
                Recognized Expert Contributor
                • Mar 2007
                • 798

                #8
                Originally posted by insertAlias
                And our forum is most definitely one of those!

                But since the OP wasn't asking for a solution, just some help, we can allow it.

                But the OP shouldn't his/her entire code. Professors have been known to browse this site, they wouldn't look to kindly to see exactly what you turned in out there on the internet. The intentions might be misunderstood as cheating.

                Okay...done some reading...so I know what you're talking about now...

                My initial thoughts on an approach to this is to find the factors, which is a very similar process to finding your prime numbers...with a couple of minor alterations... to find factors, we just test each possible divisor. We only need to check up to the square root of a value because any number divided by a divisor gives you the other divisor... so it's needless to do calculations twice (but in reverse):

                i.e. let's say we're finding factors for the value 28... we find that 4 is a factor...becaus e 28 mod 4 = 0... therefore 28 / 4 = other divisor. We already know that 1 is a factor, so automatically add that. Then check each potential divisor up to the integer part of the square root of the original value.

                Code:
                static int[] getFactors(int Value)
                {
                  list<int> factors = new list<int>;
                  factors.add(1);
                  //factors.add(Value); //"Perfect numbers" ignore the value
                  for (i = 2; i < Math.Sqrt(Value); i++)
                  {
                    if (Value % i == 0)
                    {
                      factors.add(i);
                      factors.add(Value / i)
                    }
                  }
                  return factors.ToArray();
                }
                So now all we have to do is verify if the sum of the factors in our list adds up to our original value.

                Code:
                for(i = 1; i < Long.MaxValue ; i++)
                {
                  if (i == getFactors(i).Sum() Then Console.WriteLine(i);
                }
                Console.ReadLine();
                Bear in mind that once you get past the 4th perfect number, you might be waiting a while for the next one...

                Given that you only want to go so far and that (at the time of printing) all known perfect numbers are even, we could change our loop to start at 2 and increment by 2.

                Code:
                for(i =2; i < Long.MaxValue; i = i + 2)
                Then it should work twice as fast...

                Comment

                • balabaster
                  Recognized Expert Contributor
                  • Mar 2007
                  • 798

                  #9
                  Sorry.... double post, deleted

                  Comment

                  • MrMancunian
                    Recognized Expert Contributor
                    • Jul 2008
                    • 569

                    #10
                    I worked out a short VB.NET version:

                    <complete solution removed>
                    Last edited by Curtis Rutland; Sep 26 '08, 01:17 PM. Reason: removing complete solution

                    Comment

                    • Curtis Rutland
                      Recognized Expert Specialist
                      • Apr 2008
                      • 3264

                      #11
                      MrMancunian,

                      Please read our FAQ entry on Homework Questions.

                      Since that is what this obviously is, I have removed your complete solution. We don't want to write the program for the student, that would be cheating.

                      MODERATOR

                      Comment

                      • MrMancunian
                        Recognized Expert Contributor
                        • Jul 2008
                        • 569

                        #12
                        Originally posted by insertAlias
                        MrMancunian,

                        Please read our FAQ entry on Homework Questions.

                        Since that is what this obviously is, I have removed your complete solution. We don't want to write the program for the student, that would be cheating.

                        MODERATOR
                        My sincere apologies! :-$

                        Edit: I do find that this is the responsibility of the student, and not of the forum administrators. What if someone else would be interested in this little piece of code?

                        Comment

                        • Curtis Rutland
                          Recognized Expert Specialist
                          • Apr 2008
                          • 3264

                          #13
                          Originally posted by MrMancunian
                          Edit: I do find that this is the responsibility of the student, and not of the forum administrators. What if someone else would be interested in this little piece of code?
                          That's a valid question, but we don't want to be accused of promoting scholastic dishonesty. On other threads, I wouldn't have edited you.

                          As to if others would be interested in the code, I'm sure some would. If you would like, you can write up a short article explaining the code and logic and post it in our Editor's Corner. Then it can be reviewed and made into an article.

                          Comment

                          Working...