studydotcom/ComputerScience109/PerfectNumbers.java
2025-11-28 12:06:47 -05:00

86 lines
2.7 KiB
Java

import java.util.Scanner;
/*
* The program below is a java script that helps find the perfect numbers using
* Nested Loops.
* A perfect numbersber is a positive integer that equals the sum of its
* proper positive divisors (excluding the number itself)
* */
public class PerfectNumbers {
public static void main(String[] args) {
// Part 1: Find perfect numbers between 1 and 200
System.out.println("Perfect Numbers between 1 and 200:");
// findAndPrintPerfectNumber(200);
// Add a separator line in the output.
System.out.println("\n----------------------------------------\n");
// Part 2: User input range (up to maximum of 1000)
Scanner scanner = new Scanner(System.in);
int upperBound;
do {
System.out.print("Enter an upper bound between 1 and 1000 for checking perfect numbers: ");
while (!scanner.hasNextInt()) { // Validate integer input.
System.out.println("That's not a valid number. Please enter an integer.");
scanner.next(); // discard invalid input
System.out.print("Enter an upper bound between 1 and 1000: ");
}
upperBound = scanner.nextInt();
if (upperBound < 1 || upperBound > 9000) {
System.out.println("Please enter a number between 1 and 1000.");
} else {
break;
}
} while (true);
// Now check for perfect numbers in the user-specified range.
System.out.println("\nPerfect Numbers between 1 and " + upperBound + ":");
// findAndPrintPerfectNumber(upperBound);
scanner.close();
}
/**
* This method finds and prints all perfect numbers up to a given limit
* (inclusive).
*/
public static void perfectNums() {
// Let's get the perfect numbers in the a range of positive integers ( 1 to 200)
// OUTER LOOP
for (int i = 1; i <= 200; i++) {
int total = 0;
// INNER LOOP
for (int j = 1; j <= i / 2; j++) {
total += j;
}
if (total == i) {
System.out.println(i + " is a perfect number");
}
}
}
// public static void findAndPrintPerfectNumber(int limit) {
// for (int i = 1; i <= limit; i++) { // Loop through each number
// int sumOfDivisors = 0;
//
// // Find proper divisors using nested loops.
// // Note: Instead of a nested loop, we can iterate up to half of the number,
// // but since you requested a nested loop approach, here's how it might look:
// for (int j = 1; j <= i / 2; j++) { // Only need to check up to i/2
// if (i % j == 0) {
// sumOfDivisors += j;
// }
// }
//
// // Check if the number is perfect.
// if (sumOfDivisors == i && i != 1) { // Exclude 1 as it's not considered a
// perfect number
// System.out.println(i);
// }
// }
// }
}