Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate Narcissistic numbers faster?

Tags:

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);     } } 
like image 969
Rami Jarrar Avatar asked Jan 03 '13 14:01

Rami Jarrar


People also ask

How do I get a narcissistic number?

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.

What are narcissistic decimals?

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 .

Is 4 Armstrong a 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.


1 Answers

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

like image 127
SomeWittyUsername Avatar answered Oct 22 '22 00:10

SomeWittyUsername