Peterson Number in Java

Peterson Number in Java

A Peterson number is a number that is the sum of its own digits raised to the power of the number of digits. In Java, you can use the Math.pow() method to calculate the power of a number.

import java.util.Scanner;

public class PetersonNumber {  
    public static void main(String[] args) {  
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number:");  
        int num = sc.nextInt();
        sc.close();

        int sum = 0, temp, digit;  

        temp = num;  
        while (temp != 0){  
            digit = temp % 10;  
            sum = sum + (int) Math.pow(digit, String.valueOf(num).length());  
            temp = temp/10;  
        }
            
        if(num == sum) 
            System.out.println(num + " is a Peterson number");  
        else  
            System.out.println(num + " is not a Peterson number");  
    }  
} 

The above code first takes an integer as input from the user. Then it calculates the sum of the individual digits raised to the power of the number of digits. Finally, it checks if the number given is equal to the sum calculated. If both are equal, then the number is a Peterson number. If not, then it is not a Peterson number.

Apart from the above simple algorithm, there are some other efficient algorithms to solve the Peterson number problem. One such algorithm is the “Divide and Conquer” approach. This approach divides the problem into subproblems and solves these subproblems recursively. This approach reduces the time complexity of the problem and is more efficient.

For example, a number such as 1234 can be divided into 12 + 34. Then 12 is further divided into 1 and 2, and 34 is divided into 3 and 4. The sum of the individual digits is then calculated recursively. Then the sum is compared with the original number. If both are equal, then the number is a Peterson number.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe