## Perfect Numbers |
## Loading... |

The goal of this question is to demonstrate nested loops, it might be simpler to use helper methods/function but for now just try to use two nested loops. A perfect number is any positive integer that is equal to the sum of its factors, for example 6 = 1 + 2 + 3 and is thus perfect.

Output all the perfect numbers between 1 and 10,000.
You should only find 4 of them in this range. For more information take a look at the associated wiki. |

*Try not to look at the answers until you've solved the problem. A*

*lso note that this is definitely*

**not**the most efficient way to check for factors or whether a number qualifies as perfect.
## C#:## Show Code >>int sumOfFactors = 0; //to be used to keep track of summed factors //Loops through all numbers from 1 to 10000 for (int numToCheck = 1; numToCheck < 10000; numToCheck++) { sumOfFactors = 0; //loop though all the possible factors of the number being checked for (int possibleFactor = 1; possibleFactor < numToCheck; possibleFactor++) { if (numToCheck % possibleFactor == 0) sumOfFactors = sumOfFactors + possibleFactor; } if (sumOfFactors == numToCheck) Console.WriteLine(numToCheck + " is a perfect number"); } Console.WriteLine("Press enter to exit"); Console.ReadLine(); |

## Java:## Show Code >>int sumOfFactors = 0; //to be used to keep track of summed factors //Loops through all numbers from 1 to 10000 for (int numToCheck = 1; numToCheck < 10000; numToCheck++) { sumOfFactors = 0; //loop though all the possible factors of the number being checked for (int possibleFactor = 1; possibleFactor < numToCheck; possibleFactor++) { if (numToCheck % possibleFactor == 0) sumOfFactors = sumOfFactors + possibleFactor; } if (sumOfFactors == numToCheck) System.out.println(numToCheck + " is a perfect number"); } System.out.println("Exiting now"); |

## Python:## Show Code >>#Loops through all numbers from 1 to 10000 for numToCheck in range(1,10000): sumOfFactors = 0; #to be used to keep track of summed factors #loop though all the possible factors of the number being checked for possibleFactor in range (1,numToCheck): if (numToCheck % possibleFactor == 0): sumOfFactors = sumOfFactors + possibleFactor if (sumOfFactors == numToCheck): print (numToCheck, "is a perfect number") |

Updated 2 January 2015 by Matthew F.