java
Parameters: int start, int end
start and end of the range
Returns: List of narcissistic numbers in the given range
A Java function designed to discover all Narcissistic numbers within a given range. Narcissistic numbers are those that are the sum of their own digits each raised to the power of the count of digits.
Greetings programmers! In this blog post, we will go through the intricacies involved in writing a Java function that computes narcissistic numbers within a given range. This is a great exercise to sharpen your skills in working with numbers and strings. So, grab a cup of your favorite brew and let's dive into the code!
In this step, we need to understand what's a Narcissistic number. A narcissistic number in a given number base b is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is narcissistic number, as 1^3 + 5^3 + 3^3 = 153.
So, to solve this problem we would construct a java function that takes in two integers which represent the starting and ending points of the range, and we would return all the narcissistic numbers within that range.
Start by defining the java method, findNarcissisticNumbers
, which will take two integers start
and end
as the range.
public static List<Integer> findNarcissisticNumbers(int start, int end) {
}
Now we're going to iterate over the range from start to end. We will check in each step if the number is a narcissistic number.
public static List<Integer> findNarcissisticNumbers(int start, int end) {
List<Integer> narcNums = new ArrayList<>();
for (int i = start; i <= end; i++){
}
return narcNums;
}
To check if a given number is a narcissistic number, we will convert the number into a string to easily get the number of digits. Then we will iterate over each digit and raise it to the power of the total number of digits and check if the sum is equal to the number itself.
public static List<Integer> findNarcissisticNumbers(int start, int end) {
List<Integer> narcNums = new ArrayList<>();
for (int i = start; i <= end; i++){
String num = Integer.toString(i);
int sum = 0;
int len = num.length();
for (char c : num.toCharArray()){
int digit = Character.getNumericValue(c);
sum += Math.pow(digit, len);
}
if (sum == i)
narcNums.add(i);
}
return narcNums;
}
That's it! We have now successfully programmed a function in java that finds all the narcissistic numbers in a given range. The function works by iterating over the range and checking if each number is a narcissistic number, by raising each digit to the power of the total number of digits and checking if the sum equals the original number.
Narcissistic Numbers are interesting mathematical phenomena where a number is the sum of its digits when raised to the power of the number of digits. For example in base 10, the number 153 is a narcissistic number, because `153 = 1^3 + 5^3 + 3^3`.
Learn more