The “Narcissistic numbers”, are n digit numbers where the sum of all the nth power of their digits is equal to the number.
So, 153
is a narcissistic number because 1^3 + 5^3 + 3^3 = 153
.
Now given N, find all Narcissistic numbers that are N digit length ?
My Approach : was to iterate over all numbers doing sum of powers of digits
and check if its the same number or not, and I per calculated the powers.
but that's not good enough, so is there any faster way ?!
Update: In nature there is just 88 narcissistic numbers, and the largest is 39 digits long, But I just need the numbers with length 12 or less.
My Code :
long long int powers[11][12]; // powers[x][y] is x^y. and its already calculated bool isNarcissistic(long long int x,int n){ long long int r = x; long long int sum = 0; for(int i=0; i<n ; ++i){ sum += powers[x%10][n]; if(sum > r) return false; x /= 10; } return (sum == r); } void find(int n,vector<long long int> &vv){ long long int start = powers[10][n-1]; long long int end = powers[10][n]; for(long long int i=start ; i<end ; ++i){ if(isNarcissistic(i,n)) vv.push_back(i); } }
Narcissistic Numbers are defined as follows: An n digit number is narcissistic if the sum of its digits to the nth power equal the original number. For example with 2 digits, say I choose the number 36: 32 + 62 = 45.
A Narcissistic decimal number is a non-negative integer, n that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. and so 153 is a narcissistic decimal number .
Let us now look at what is Armstrong number behavior with a 4 digit Armstrong number. The operation involves raising each of the digits to the power of 4 and then totaling the terms obtained. Armstrong numbers with 4 digits are 1634, 8208, and 9474 among others.
Since there are only 88 narcisstic numbers in total, you can just store them in a look up table and iterate over it: http://mathworld.wolfram.com/NarcissisticNumber.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With