Skip to content
the poor coder

Peterson Number in Java

Poor Man
Published
Reading time
2 min read

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.

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC