Number of daffodils (Java)

Posted by Goldeneye on Tue, 03 Dec 2019 06:42:53 +0100

Title:

* find out all "Narcissus numbers" between 0-999 and output. "Narcissus number" refers to a three digit number,
* the sum of the cubes of the numbers is exactly equal to the number itself, for example, 153 = 1 + 5 + 3?, 153 is a "narcissus number"
 * 
* in number theory, Narcissistic number is also called Narcissistic number, self power number, Armstrong number or Armstrong number,
* refers to an N-digit number whose N-th power sum of each number is equal to the number.  
* for example, 153 is a three digit number of Narcissus, the sum of the cubes of which is equal to the number:
 * 153 = 1^3 + 5^3 + 3^3.  

 

Train of thought:

Find out the numbers in the numbers respectively, and judge whether the sum of the powers is equal to the original number

 

Code:
 

package com.datastructure.other;

import java.util.ArrayList;
import java.util.List;

/**
 * Find out all "narcissus number" between 0-999 and output. "Narcissus number" refers to a three digit number,
 * The sum of the cubes of the numbers is exactly equal to the number itself. For example, if 153 = 1 + 5 + 3?, 153 is a narcissus number 
 * 
 * In number theory, Narcissistic number is also called Narcissistic number, self power number, Armstrong number or Armstrong number,
 * It refers to an n-digit number, and the sum of the N-power of each number is equal to the number. 
 * For example, 153 is a three digit number of Narcissus, the sum of the cubes of which is equal to this number: 
 * 153 = 1^3 + 5^3 + 3^3.  
 *
 */
public class NarcissisticNumber {

	/**
	 * Get the number of daffodils before 0-999 
	 */
	public static List<Integer> getNarcissisticNumber() {
		List<Integer> lst = new ArrayList<>();
		
		int start = 0;
		int end = 999;
		
		for (int i = start; i <= end; i++) {
			if (isNarcissisticNumber(i, start, end)) {
				lst.add(i);
			}
		}
		
		return lst;
	}
	
	private static boolean isNarcissisticNumber(int num, int start, int end) {
		if (num < start || num > end) {
			return false;
		}
		
		// Get the number of digits
		int count = 0;
		if (num < 10) {
			count = 1;
		} else if (num < 100) {
			count = 2;
		} else {
			count = 3;
		}
		
		int i = num;
		int sum = 0;
		while (i > 0) {
			// Power of last digit
			sum += Math.pow(i % 10, count);
			// Number divided by 10
			i /= 10;
		}
		
		return sum == num;
	}
	
	public static void main(String[] args) {
		System.out.println(getNarcissisticNumber());
	}

}

 

Reference resources:

Number of Narcissus: https://blog.csdn.net/wang_0712/article/details/80279806

Extension:

21 Narcissus: https://blog.csdn.net/bear_huangzhen/article/details/78465111

Topics: Java