Write a program to enter the 1st 20 perfect numbers in an 1D array. Use For loop.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Ritwika
    New Member
    • Jul 2010
    • 1

    #1

    Write a program to enter the 1st 20 perfect numbers in an 1D array. Use For loop.

    use for loops to do it. or if u cant..then do it neway u want.
  • sixdonuts
    New Member
    • Jul 2010
    • 6

    #2
    I'll give you the code to check to see if a number is perfect. It might not work perfectly, I haven't run it. I think it's close, it could have floating point problems?

    Code:
    public boolean isPerfect(int n)
    {
      ArrayList<Integer> divisors = new ArrayList<Integer>();
    
      double d;
    
      for (int i = 1; i < n; i++)
      {
        d = n/i;
        if (d == (double)Math.round(d))
          divisors.add(i);
      }
    
      int sum = 0;
      for (Integer i : divisors)
        sum += i;
    
      if (sum == n)
        return true;
      return false;
    
    }

    Comment

    Working...