From 219c51df4142ade9111580bbf3aa433003194463 Mon Sep 17 00:00:00 2001 From: piyushkumar0707 <121piyush466mits@gmail.com> Date: Sun, 19 Oct 2025 02:20:42 +0530 Subject: [PATCH] feat: add Java program to check perfect number - Comprehensive tutorial with 5 different approaches - Basic method with complete divisor enumeration - Optimized approach using square root optimization - Range finder to discover multiple perfect numbers - Euclid's formula for generating even perfect numbers - Interactive explorer with menu-driven interface - Mathematical background and known perfect numbers - Performance analysis and complexity comparison - Educational content about Mersenne primes --- content/programs/contents.mdx | 21 +- .../java-program-to-check-perfect-number.mdx | 459 ++++++++++++++++++ content/programs/meta.json | 1 + src/app/(site)/about/page.tsx | 4 +- src/app/(site)/legal/privacy/page.tsx | 19 +- src/app/(site)/legal/terms/page.tsx | 29 +- src/app/(site)/sponsors/page.tsx | 4 +- src/app/api/playground/route.ts | 38 +- src/app/global.css | 2 +- src/components/home/index.ts | 1 - src/hooks/index.ts | 2 +- 11 files changed, 523 insertions(+), 57 deletions(-) create mode 100644 content/programs/java-program-to-check-perfect-number.mdx diff --git a/content/programs/contents.mdx b/content/programs/contents.mdx index 582f830f..94c75cf8 100644 --- a/content/programs/contents.mdx +++ b/content/programs/contents.mdx @@ -8,13 +8,14 @@ description: A collection of basic Java programs categorized by topic. 1. [Print an Integer](/programs/print-an-integer) 2. [Add Two Integers](/programs/add-two-integers) 3. [Check Even or Odd Number](/programs/check-even-or-odd) -4. [Add Two Binary](/programs/java-program-to-add-two-binary-numbers) -5. [Add Two Complex Numbers](/programs/java-program-to-add-two-complex-numbers) -6. [Multiply Two Numbers](/programs/multiply-two-numbers) -7. [Check Leap Year](/programs/java-program-to-check-Leap-year) -8. [Calculate Simple interest](/programs/calculate-simple-interest) -9. [Check Divisibility](/programs/java-program-to-check-divisbility) -10. [Calculate Quotient and Reminder](/programs/find-quotient-and-reminder) -11. [Calculate Power of a Number](/programs/calculate-power-of-a-number) -12. [Calculate Compound Interest](/programs/calculate-compound-interest) -13. [Calculate Factorial of a Number](/programs/factorial-in-java) +4. [Java Program to Check Perfect Number](/programs/java-program-to-check-perfect-number) +5. [Add Two Binary](/programs/java-program-to-add-two-binary-numbers) +6. [Add Two Complex Numbers](/programs/java-program-to-add-two-complex-numbers) +7. [Multiply Two Numbers](/programs/multiply-two-numbers) +8. [Check Leap Year](/programs/java-program-to-check-Leap-year) +9. [Calculate Simple interest](/programs/calculate-simple-interest) +10. [Check Divisibility](/programs/java-program-to-check-divisbility) +11. [Calculate Quotient and Reminder](/programs/find-quotient-and-reminder) +12. [Calculate Power of a Number](/programs/calculate-power-of-a-number) +13. [Calculate Compound Interest](/programs/calculate-compound-interest) +14. [Calculate Factorial of a Number](/programs/factorial-in-java) diff --git a/content/programs/java-program-to-check-perfect-number.mdx b/content/programs/java-program-to-check-perfect-number.mdx new file mode 100644 index 00000000..fa27fd2f --- /dev/null +++ b/content/programs/java-program-to-check-perfect-number.mdx @@ -0,0 +1,459 @@ +--- +title: Java Program to Check Perfect Number +description: Learn to identify perfect numbers in Java with multiple methods, optimizations, and comprehensive examples. +--- + +## Introduction + +A **Perfect Number** is a positive integer that is equal to the sum of its proper positive divisors (excluding the number itself). Perfect numbers are rare and have fascinated mathematicians for centuries. + +**Examples:** + +- **6** is perfect: divisors are 1, 2, 3 → 1 + 2 + 3 = 6 +- **28** is perfect: divisors are 1, 2, 4, 7, 14 → 1 + 2 + 4 + 7 + 14 = 28 +- **496** is perfect: sum of divisors equals 496 + +This tutorial demonstrates multiple approaches to check perfect numbers in Java, from basic to optimized solutions. + +## Method 1: Basic Approach with Complete Divisor Check + +This straightforward method finds all divisors by checking every number from 1 to n-1. + +```java +import java.util.Scanner; +import java.util.ArrayList; + +public class PerfectNumberBasic { + + public static boolean isPerfectNumber(int number) { + if (number <= 1) { + return false; // Perfect numbers are positive and > 1 + } + + int sum = 0; + ArrayList divisors = new ArrayList<>(); + + // Find all proper divisors (1 to number-1) + for (int i = 1; i < number; i++) { + if (number % i == 0) { + divisors.add(i); + sum += i; + } + } + + // Display divisors for educational purposes + System.out.print("Divisors of " + number + ": "); + for (int divisor : divisors) { + System.out.print(divisor + " "); + } + System.out.println("\nSum of divisors: " + sum); + + return sum == number; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter a number to check if it's perfect: "); + int number = scanner.nextInt(); + + if (isPerfectNumber(number)) { + System.out.println(number + " is a Perfect Number! ✓"); + } else { + System.out.println(number + " is not a Perfect Number."); + } + + scanner.close(); + } +} +``` + +**Sample Output:** + +``` +Enter a number to check if it's perfect: 28 +Divisors of 28: 1 2 4 7 14 +Sum of divisors: 28 +28 is a Perfect Number! ✓ +``` + +## Method 2: Optimized Approach (Up to Square Root) + +This optimized version reduces time complexity by only checking divisors up to the square root. + +```java +import java.util.Scanner; + +public class PerfectNumberOptimized { + + public static boolean isPerfectNumber(int number) { + if (number <= 1) { + return false; + } + + int sum = 1; // 1 is always a divisor (except for 1 itself) + + // Check divisors up to square root + for (int i = 2; i * i <= number; i++) { + if (number % i == 0) { + sum += i; // Add the divisor + + // Add the corresponding divisor (number/i) + // but avoid adding the square root twice + if (i * i != number) { + sum += number / i; + } + } + } + + return sum == number; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter a number to check: "); + int number = scanner.nextInt(); + + long startTime = System.nanoTime(); + boolean result = isPerfectNumber(number); + long endTime = System.nanoTime(); + + if (result) { + System.out.println(number + " is a Perfect Number!"); + } else { + System.out.println(number + " is not a Perfect Number."); + } + + System.out.println("Execution time: " + (endTime - startTime) + " nanoseconds"); + + scanner.close(); + } +} +``` + +## Method 3: Find All Perfect Numbers in a Range + +This program finds all perfect numbers within a specified range. + +```java +import java.util.Scanner; +import java.util.ArrayList; + +public class FindPerfectNumbers { + + public static boolean isPerfectNumber(int number) { + if (number <= 1) return false; + + int sum = 1; + for (int i = 2; i * i <= number; i++) { + if (number % i == 0) { + sum += i; + if (i * i != number) { + sum += number / i; + } + } + } + return sum == number; + } + + public static ArrayList findPerfectNumbersInRange(int start, int end) { + ArrayList perfectNumbers = new ArrayList<>(); + + for (int i = start; i <= end; i++) { + if (isPerfectNumber(i)) { + perfectNumbers.add(i); + } + } + + return perfectNumbers; + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.print("Enter the start of range: "); + int start = scanner.nextInt(); + + System.out.print("Enter the end of range: "); + int end = scanner.nextInt(); + + System.out.println("\nSearching for perfect numbers from " + start + " to " + end + "..."); + + ArrayList perfectNumbers = findPerfectNumbersInRange(start, end); + + if (perfectNumbers.isEmpty()) { + System.out.println("No perfect numbers found in the given range."); + } else { + System.out.println("Perfect numbers found: " + perfectNumbers); + System.out.println("Total count: " + perfectNumbers.size()); + } + + scanner.close(); + } +} +``` + +**Sample Output:** + +``` +Enter the start of range: 1 +Enter the end of range: 1000 + +Searching for perfect numbers from 1 to 1000... +Perfect numbers found: [6, 28, 496] +Total count: 3 +``` + +## Method 4: Using Euclid's Formula for Even Perfect Numbers + +Euclid discovered that every even perfect number has the form 2^(p-1) × (2^p - 1), where 2^p - 1 is prime. + +```java +import java.util.Scanner; + +public class EuclidPerfectNumbers { + + // Check if a number is prime + public static boolean isPrime(long number) { + if (number < 2) return false; + if (number == 2) return true; + if (number % 2 == 0) return false; + + for (long i = 3; i * i <= number; i += 2) { + if (number % i == 0) { + return false; + } + } + return true; + } + + // Generate perfect number using Euclid's formula + public static long generatePerfectNumber(int p) { + if (!isPrime(p)) { + return -1; // p must be prime + } + + long mersennePrime = (1L << p) - 1; // 2^p - 1 + + if (!isPrime(mersennePrime)) { + return -1; // 2^p - 1 must also be prime (Mersenne prime) + } + + return (1L << (p - 1)) * mersennePrime; // 2^(p-1) × (2^p - 1) + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.println("Generate Perfect Numbers using Euclid's Formula"); + System.out.println("Formula: 2^(p-1) × (2^p - 1), where p and (2^p - 1) are both prime"); + + System.out.print("\nEnter value of p (prime number): "); + int p = scanner.nextInt(); + + long perfectNumber = generatePerfectNumber(p); + + if (perfectNumber == -1) { + System.out.println("Cannot generate perfect number with p = " + p); + System.out.println("Either " + p + " is not prime, or 2^" + p + " - 1 is not prime."); + } else { + System.out.println("Perfect number generated: " + perfectNumber); + + // Verify it's actually perfect + System.out.println("Verification: " + (isPerfectNumberOptimized(perfectNumber) ? "✓ Confirmed" : "✗ Error")); + } + + // Show first few perfect numbers using known Mersenne primes + System.out.println("\nFirst few perfect numbers:"); + int[] mersennePrimes = {2, 3, 5, 7, 13, 17, 19}; // Known Mersenne prime exponents + + for (int prime : mersennePrimes) { + long perfect = generatePerfectNumber(prime); + if (perfect != -1 && perfect < Long.MAX_VALUE / 2) { + System.out.println("p=" + prime + ": " + perfect); + } + } + + scanner.close(); + } + + private static boolean isPerfectNumberOptimized(long number) { + if (number <= 1) return false; + + long sum = 1; + for (long i = 2; i * i <= number; i++) { + if (number % i == 0) { + sum += i; + if (i * i != number) { + sum += number / i; + } + } + } + return sum == number; + } +} +``` + +## Method 5: Interactive Perfect Number Explorer + +A comprehensive program that combines all methods with a user-friendly menu. + +```java +import java.util.Scanner; +import java.util.ArrayList; + +public class PerfectNumberExplorer { + + public static boolean isPerfectNumber(int number) { + if (number <= 1) return false; + + int sum = 1; + for (int i = 2; i * i <= number; i++) { + if (number % i == 0) { + sum += i; + if (i * i != number) { + sum += number / i; + } + } + } + return sum == number; + } + + public static void displayDivisors(int number) { + System.out.print("Proper divisors of " + number + ": "); + ArrayList divisors = new ArrayList<>(); + int sum = 0; + + for (int i = 1; i < number; i++) { + if (number % i == 0) { + divisors.add(i); + sum += i; + } + } + + for (int divisor : divisors) { + System.out.print(divisor + " "); + } + System.out.println("\nSum: " + sum + " (Number: " + number + ")"); + } + + public static void findInRange(int start, int end) { + System.out.println("Perfect numbers from " + start + " to " + end + ":"); + boolean found = false; + + for (int i = start; i <= end; i++) { + if (isPerfectNumber(i)) { + System.out.print(i + " "); + found = true; + } + } + + if (!found) { + System.out.print("None found"); + } + System.out.println(); + } + + public static void showKnownPerfectNumbers() { + System.out.println("First few known perfect numbers:"); + System.out.println("6 (2^1 × 3)"); + System.out.println("28 (2^2 × 7)"); + System.out.println("496 (2^4 × 31)"); + System.out.println("8128 (2^6 × 127)"); + System.out.println("33550336 (2^12 × 8191)"); + } + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + while (true) { + System.out.println("\n=== Perfect Number Explorer ==="); + System.out.println("1. Check if a number is perfect"); + System.out.println("2. Show divisors of a number"); + System.out.println("3. Find perfect numbers in range"); + System.out.println("4. Show known perfect numbers"); + System.out.println("5. Exit"); + System.out.print("Choose an option: "); + + int choice = scanner.nextInt(); + + switch (choice) { + case 1: + System.out.print("Enter number to check: "); + int num = scanner.nextInt(); + if (isPerfectNumber(num)) { + System.out.println(num + " is a Perfect Number! ✓"); + } else { + System.out.println(num + " is not a Perfect Number."); + } + break; + + case 2: + System.out.print("Enter number to show divisors: "); + int divisorNum = scanner.nextInt(); + displayDivisors(divisorNum); + break; + + case 3: + System.out.print("Enter start range: "); + int start = scanner.nextInt(); + System.out.print("Enter end range: "); + int end = scanner.nextInt(); + findInRange(start, end); + break; + + case 4: + showKnownPerfectNumbers(); + break; + + case 5: + System.out.println("Thank you for exploring perfect numbers!"); + scanner.close(); + return; + + default: + System.out.println("Invalid choice. Please try again."); + } + } + } +} +``` + +## Mathematical Background + +### **What Makes a Number Perfect?** + +A perfect number n satisfies: **σ(n) - n = n**, where σ(n) is the sum of all divisors including n itself. + +### **Known Facts:** + +1. **Even Perfect Numbers**: All known perfect numbers are even +2. **Euclid's Theorem**: Every even perfect number has the form 2^(p-1) × (2^p - 1) +3. **Mersenne Primes**: When 2^p - 1 is prime, it's called a Mersenne prime +4. **Rarity**: Only 51 perfect numbers are known as of 2024 + +### **First Few Perfect Numbers:** + +- 6 = 2^1 × (2^2 - 1) = 2 × 3 +- 28 = 2^2 × (2^3 - 1) = 4 × 7 +- 496 = 2^4 × (2^5 - 1) = 16 × 31 +- 8128 = 2^6 × (2^7 - 1) = 64 × 127 + +## Time and Space Complexity + +| Method | Time Complexity | Space Complexity | Best For | +| ---------------- | --------------- | ---------------------------- | ------------------------- | +| Basic | O(n) | O(k) where k = divisor count | Learning/Small numbers | +| Optimized | O(√n) | O(1) | General use | +| Range Search | O(m × √n) | O(1) | Finding multiple | +| Euclid's Formula | O(√p) | O(1) | Generating large perfects | + +## Practice Exercises + +1. **Abundant vs Perfect vs Deficient**: Classify numbers based on sum of proper divisors +2. **Perfect Number Factorization**: Show the prime factorization of perfect numbers +3. **Near-Perfect Numbers**: Find numbers where sum of proper divisors = n ± 1 +4. **Performance Comparison**: Benchmark different methods for large numbers + +Perfect numbers beautifully demonstrate the intersection of mathematics and programming, making them excellent for learning algorithmic thinking! diff --git a/content/programs/meta.json b/content/programs/meta.json index 0279544f..9d626816 100644 --- a/content/programs/meta.json +++ b/content/programs/meta.json @@ -17,6 +17,7 @@ "---Conditional Checks---", "check-even-or-odd", + "java-program-to-check-perfect-number", "java-program-to-check-divisibility", "java-program-to-check-Leap-year", "java-program-to-check-whether-input-character-is-vowel-or-consonant", diff --git a/src/app/(site)/about/page.tsx b/src/app/(site)/about/page.tsx index 23544530..93ae7aa1 100644 --- a/src/app/(site)/about/page.tsx +++ b/src/app/(site)/about/page.tsx @@ -142,8 +142,8 @@ export default function AboutPage() { > Our platform bridges complex Java concepts with real-world application through interactive tutorials, hands-on exercises, and - structured learning paths. Whether you're a complete beginner or - experienced developer, our community-driven approach ensures + structured learning paths. Whether you're a complete beginner + or experienced developer, our community-driven approach ensures accessible, practical learning for everyone. diff --git a/src/app/(site)/legal/privacy/page.tsx b/src/app/(site)/legal/privacy/page.tsx index 8249f6cc..4810122c 100644 --- a/src/app/(site)/legal/privacy/page.tsx +++ b/src/app/(site)/legal/privacy/page.tsx @@ -21,10 +21,11 @@ export default function PrivacyPolicyPage(): React.ReactElement {

1. Introduction

- Welcome to Javaistic ("we," "our," or "us"). We are committed to - protecting your privacy and ensuring transparency. This Privacy Policy - explains our practices regarding information handling on our open - source educational platform for learning Java programming. + Welcome to Javaistic ("we," "our," or + "us"). We are committed to protecting your privacy and + ensuring transparency. This Privacy Policy explains our practices + regarding information handling on our open source educational platform + for learning Java programming.

Important: Javaistic does not require user accounts @@ -69,8 +70,8 @@ export default function PrivacyPolicyPage(): React.ReactElement { If you choose to contribute to the Javaistic project through our public GitHub repository, any information you provide (such as GitHub username, email for commits, or pull request content) will be handled - according to GitHub's privacy policies and our open source licensing - terms. + according to GitHub's privacy policies and our open source + licensing terms.

4. How We Use Information

@@ -129,9 +130,9 @@ export default function PrivacyPolicyPage(): React.ReactElement {

Javaistic is an educational platform intended for learners of all ages interested in Java programming. Since we do not collect personal - information, there are no special considerations for children's data. - However, we recommend that children under 13 have parental guidance - when accessing technical content. + information, there are no special considerations for children's + data. However, we recommend that children under 13 have parental + guidance when accessing technical content.

8. International Users

diff --git a/src/app/(site)/legal/terms/page.tsx b/src/app/(site)/legal/terms/page.tsx index 7b4b8d87..73f1621a 100644 --- a/src/app/(site)/legal/terms/page.tsx +++ b/src/app/(site)/legal/terms/page.tsx @@ -21,11 +21,12 @@ export default function TermsPage(): React.ReactElement {

1. Acceptance of Terms

- By accessing and using Javaistic ("the Platform," "we," "our," or - "us"), an open source educational platform for learning Java - programming, you accept and agree to be bound by the terms and - provision of this agreement ("Terms of Service" or "Terms"). If you do - not agree to abide by these terms, please do not use this platform. + By accessing and using Javaistic ("the Platform," + "we," "our," or "us"), an open source + educational platform for learning Java programming, you accept and + agree to be bound by the terms and provision of this agreement + ("Terms of Service" or "Terms"). If you do not + agree to abide by these terms, please do not use this platform.

2. Description of Service

@@ -86,8 +87,8 @@ export default function TermsPage(): React.ReactElement {
  • Upload viruses, malware, or other harmful code
  • Post content that is unlawful, harmful, threatening, abusive, - harassing, defamatory, vulgar, obscene, or invasive of another's - privacy + harassing, defamatory, vulgar, obscene, or invasive of + another's privacy
  • Impersonate any person or entity or misrepresent your affiliation @@ -97,9 +98,10 @@ export default function TermsPage(): React.ReactElement {

    4.2 Educational Use

    The Platform is intended for educational purposes. While we strive to - provide accurate information, all content is provided "as is" for - learning purposes. Users should verify information independently and - use proper judgment when applying concepts learned here. + provide accurate information, all content is provided "as + is" for learning purposes. Users should verify information + independently and use proper judgment when applying concepts learned + here.

    5. Content and Contributions

    @@ -197,9 +199,10 @@ export default function TermsPage(): React.ReactElement {

    8. Disclaimers

    8.1 Service Availability

    - The Platform is provided on an "as is" and "as available" basis. As an - open source project maintained by volunteers, we do not guarantee that - the Platform will be uninterrupted, timely, secure, or error-free. + The Platform is provided on an "as is" and "as + available" basis. As an open source project maintained by + volunteers, we do not guarantee that the Platform will be + uninterrupted, timely, secure, or error-free.

    8.2 Educational Content

    diff --git a/src/app/(site)/sponsors/page.tsx b/src/app/(site)/sponsors/page.tsx index 68725982..3eb03c96 100644 --- a/src/app/(site)/sponsors/page.tsx +++ b/src/app/(site)/sponsors/page.tsx @@ -261,8 +261,8 @@ export default function SponsorsPage() {

    Growing Platform

  • - Support a platform that's helping developers learn and grow in the - Java ecosystem. + Support a platform that's helping developers learn and grow + in the Java ecosystem.

    ✓ Growing platform reach diff --git a/src/app/api/playground/route.ts b/src/app/api/playground/route.ts index d30837b2..a4de13d7 100644 --- a/src/app/api/playground/route.ts +++ b/src/app/api/playground/route.ts @@ -1,41 +1,43 @@ // src/app/api/run-java/route.ts -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; export async function POST(req: Request) { try { const { code } = await req.json(); - const response = await fetch('https://api.jdoodle.com/v1/execute', { - method: 'POST', + const response = await fetch("https://api.jdoodle.com/v1/execute", { + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify({ script: code, - language: 'java', - versionIndex: '3', // Java 11 - clientId: '' ,// ← replace with your actual clientId - clientSecret: '', // ← replace with your actual clientSecret + language: "java", + versionIndex: "3", // Java 11 + clientId: "", // ← replace with your actual clientId + clientSecret: "", // ← replace with your actual clientSecret }), }); const data = await response.json(); - return new NextResponse(JSON.stringify({ - run: { - output: data.output || 'No output', + return new NextResponse( + JSON.stringify({ + run: { + output: data.output || "No output", + }, + }), + { + status: 200, + headers: { "Content-Type": "application/json" }, }, - }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - + ); } catch (err) { console.error(err); - return new NextResponse(JSON.stringify({ error: 'Execution failed' }), { + return new NextResponse(JSON.stringify({ error: "Execution failed" }), { status: 500, - headers: { 'Content-Type': 'application/json' }, + headers: { "Content-Type": "application/json" }, }); } } diff --git a/src/app/global.css b/src/app/global.css index 9733484d..63819f81 100644 --- a/src/app/global.css +++ b/src/app/global.css @@ -159,4 +159,4 @@ kbd { #nd-nav { @apply hover:bg-background border-none bg-black/10 backdrop-blur-md transition-all duration-300 ease-in-out sm:top-2 sm:mx-auto sm:max-w-5xl sm:rounded-2xl; -} \ No newline at end of file +} diff --git a/src/components/home/index.ts b/src/components/home/index.ts index cdfa850e..45c8c562 100644 --- a/src/components/home/index.ts +++ b/src/components/home/index.ts @@ -13,4 +13,3 @@ export { FeatureCard } from "./feature-card"; // Export constants export { ANIMATION_VARIANTS, HOVER_ANIMATIONS } from "./animation-variants"; - diff --git a/src/hooks/index.ts b/src/hooks/index.ts index ceb1837e..085de0f7 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -1,2 +1,2 @@ export { useGitHubStats } from "./useGitHubStats"; -export { useDarkMode } from "./useDarkMode"; \ No newline at end of file +export { useDarkMode } from "./useDarkMode";