• About

Metazz

~ It's not Metal, it's not Jazz

Metazz

Category Archives: mathematics

Narcissistic Numbers, The Java Code Edition

05 Thursday Jun 2014

Posted by Alan Shanahan in computing, mathematics

≈ Leave a comment

Tags

code, fun, java, math, mathematics, maths, narcissistic numbers, number, numbers, recreational mathematics

Finally, I pulled my finger out of somewhere and wrote some Java code to calculate all Narcissistic Numbers. I ran it for numbers up to 9 digits and it took about 30 minutes in total. The time taken will increase exponentially, the more digits you run it for.

I’m sure you code/number buffs out there could write a more elegant solution to the problem – please let me know if you do.

Here’s a sample of the output from this code;

DIGITS: 3
153
370
371
407
DIGITS: 4
1634
8208
9474
DIGITS: 5
54748
92727
93084
DIGITS: 6
548834
DIGITS: 7
1741725
4210818
9800817
9926315
DIGITS: 8
24678050
24678051
88593477
DONE.

Or if you decide to run this, let me know how far you got. Here is the breakdown of the code, followed by the full class for you to copy/paste.

Let’s use some math libraries to make the job easier:

import java.math.BigDecimal;  // We need this class for the correct level of precision
import java.math.MathContext; // This class is used to by BigDecimal methods to determine precision

We define the starting and ending number of digits to process:

public class NarcissismItself {

	static final int LO_RANGE = 3;  // From this number of digits...
	static final int HI_RANGE = 8;  // ...to this number of digits.
	// Maximum 39. No Narcissistic numbers from 40 digits. Mathematical fact.
	// After 9, it can take a long time to run.

	static final int CHAR0 = Integer.valueOf((char)'0');  // Used later to calculate char/int conversion offset

The outer loop iterates through the numbers of digits we wish to process:

	public static void main(String[] args) {

		Integer iDigits = LO_RANGE;
		do {                                       // Iterate through the required numbers of digits
			iterateNarcissisticNumbers(iDigits);
			iDigits++;
		} while (iDigits <= HI_RANGE);

		System.out.println("DONE.");

	}

We work out the start and ending number for the number of digits in the current iteration:

	private static void iterateNarcissisticNumbers(Integer iDigits) {

		System.out.print("DIGITS: ");
		System.out.print(iDigits);
		System.out.println();

		// Calculate starting number, based on digits e.g. 7 digits = 1000000
		BigDecimal bdLo = new BigDecimal(10).pow(iDigits-1, new MathContext(40));
		// Calculate ending number, based on digits e.g. 7 digits = 9999999
		BigDecimal bdHi = new BigDecimal(10).pow(iDigits, new MathContext(40)).subtract(new BigDecimal(1));
		bdLo.setScale(0); // No decimals
		bdHi.setScale(0); // No decimals
		
		// Check all numbers between starting and ending numbers
		checkNarcissisticNumber(bdLo, bdHi, iDigits);
		
	}

We iterate through each number in the range and check whether each is Narcissistic:

	private static void checkNarcissisticNumber(BigDecimal bdLo, BigDecimal bdHi, int iDigits) {

		BigDecimal bdLoop = bdLo.subtract(new BigDecimal(1));
		do {                                                   // For all candidate numbers, check whether Narcissistic
			bdLoop = bdLoop.add(new BigDecimal(1));
			check1NarcissisticNumber(bdLoop, iDigits);
		} while ((bdLoop.compareTo(bdHi) == -1));

	}

Here’s the code that checks an individual number for Narcissism:

	private static void check1NarcissisticNumber(BigDecimal bdNumber, int iDigits) {

		BigDecimal accumulation = new BigDecimal(0);

		for (char sX : bdNumber.toPlainString().toCharArray()) {  // Iterate through all digits
			int charVal = Integer.valueOf(sX)-CHAR0;              // Convert char to int
			BigDecimal accum = new BigDecimal(charVal).pow(iDigits,new MathContext(40)); // Raise to power based on digits
			accumulation = accumulation.add(accum);               // Add to accumulated figure
		}

		if (bdNumber.compareTo(accumulation) == 0) {    // Is the accumulated number the same as the original number?
			System.out.print(bdNumber.toPlainString()); // Yes? Then it is Narcissistic.
			System.out.println();
		}
	
	}

Finally, we close off the class code block:

}

The full class is here in its entirety:

import java.math.BigDecimal;  // We need this class for the correct level of precision
import java.math.MathContext; // This class is used to by BigDecimal methods to determine precision

public class NarcissismItself {

	static final int LO_RANGE = 3;  // From this number of digits...
	static final int HI_RANGE = 8;  // ...to this number of digits.
	// Maximum 39. No Narcissistic numbers from 40 digits. Mathematical fact.
	// After 9, it can take a long time to run.

	static final int CHAR0 = Integer.valueOf((char)'0');  // Used later to calculate char/int conversion offset

	//--------------------------------------
	public static void main(String[] args) {

		Integer iDigits = LO_RANGE;
		do {                                       // Iterate through the required numbers of digits
			iterateNarcissisticNumbers(iDigits);
			iDigits++;
		} while (iDigits <= HI_RANGE);

		System.out.println("DONE.");

	}

	//---------------------------------------------------------------
	private static void iterateNarcissisticNumbers(Integer iDigits) {

		System.out.print("DIGITS: ");
		System.out.print(iDigits);
		System.out.println();

		// Calculate starting number, based on digits e.g. 7 digits = 1000000
		BigDecimal bdLo = new BigDecimal(10).pow(iDigits-1, new MathContext(40));
		// Calculate ending number, based on digits e.g. 7 digits = 9999999
		BigDecimal bdHi = new BigDecimal(10).pow(iDigits, new MathContext(40)).subtract(new BigDecimal(1));
		bdLo.setScale(0); // No decimals
		bdHi.setScale(0); // No decimals
		
		// Check all numbers between starting and ending numbers
		checkNarcissisticNumber(bdLo, bdHi, iDigits);
		
	}

	//------------------------------------------------------------------------------------------
	private static void checkNarcissisticNumber(BigDecimal bdLo, BigDecimal bdHi, int iDigits) {

		BigDecimal bdLoop = bdLo.subtract(new BigDecimal(1));
		do {                                                   // For all candidate numbers, check whether Narcissistic
			bdLoop = bdLoop.add(new BigDecimal(1));
			check1NarcissisticNumber(bdLoop, iDigits);
		} while ((bdLoop.compareTo(bdHi) == -1));

	}

	//------------------------------------------------------------------------------
	private static void check1NarcissisticNumber(BigDecimal bdNumber, int iDigits) {

		BigDecimal accumulation = new BigDecimal(0);

		for (char sX : bdNumber.toPlainString().toCharArray()) {  // Iterate through all digits
			int charVal = Integer.valueOf(sX)-CHAR0;              // Convert char to int
			BigDecimal accum = new BigDecimal(charVal).pow(iDigits,new MathContext(40)); // Raise to power based on digits
			accumulation = accumulation.add(accum);               // Add to accumulated figure
		}

		if (bdNumber.compareTo(accumulation) == 0) {    // Is the accumulated number the same as the original number?
			System.out.print(bdNumber.toPlainString()); // Yes? Then it is Narcissistic.
			System.out.println();
		}
	
	}

}
Advertisement

I Love Narcissistic Numbers

26 Sunday Jan 2014

Posted by Alan Shanahan in mathematics

≈ 2 Comments

Tags

fun, math, mathematics, maths, narcissistic numbers, number, numbers, recreational mathematics

Ever since school I’ve loved the pure truth of mathematics. The fact that you can be just right or wrong, with no middle ground or ambiguity, always appealed to me. As a toolset, it sits neatly in one’s arse pocket, ready to be used throughout life.

Recreational Mathematics can introduce some fun into the subject. I was listening to a podcast of The Infinite Monkey Cage a few days ago and a guest introduced the concept of Narcissistic Numbers – numbers that are in love with themselves. Here’s an example:

The four-digit number 8208.
Take each digit, raise it to the fourth power (because there are four digits), added the numbers and you get … 8208.

To work it out:
(8^4)+(2^4)+(0^4)+(8^4)
= (8x8x8x8)+(2x2x2x2)+(0x0x0x0)+(8x8x8x8)
= 4096+16+0+4096
= 8208

The number loved itself so much, it turned back into itself.

There are only three four-digit numbers that are Narcissistic Numbers. Same with five digit numbers. I’m busy writing some Java code to calculate them for everything up to 39 digits. There is a 39-digit Narcissistic Number, the largest possible:

115,132,219,018,763,992,565,095,597,973,971,522,401

The amazing thing is that it can be proven fairly easily that there are no numbers above 39 digits that are Narcissistic. The proof is this:

Take the largest 39-digit number, which is 999,999,999,999,999,999,999,999,999,999,999,999,999

Perform the calculation on this i.e. add 9 to the 39th power to itself 39 times, or
(9^39) + (9^39) + (9^39) + (9^39) + … + (9^39) + (9^39) + (9^39)
the above 39 times
= 39 x (9^39)
= 640,504,927,462,165,500,000,000,000,000,000,000,000 (approx.)

Note that my calculator only has a limited precision to a certain number of digits (around 16). But it is sufficient to demonstrate the proof: the number, itself 39 digits, is considerably less than the largest 39-digit number i.e. it is deficient in that it cannot produce a number large enough to equal the originating number. A 40-digit number is going to have the same problem, in fact even more so, as is a 41-digit number, and so on.

I dunno about you, but I love the idea that (a) this is possible and (b) someone thought of it. Also, because this is an exploration of numbers in Base 10 (i.e. a man-made condition) it would be worth exploring in other bases for comparison.

Numbers for numbers’ sake. Love it.

It’s not big or clever

Sometimes serious, sometimes not. Work it out.

Archives

  • June 2014
  • May 2014
  • January 2014
  • December 2013
  • October 2013
  • September 2013

Recent Posts

  • Narcissistic Numbers, The Java Code Edition
  • You MUST accept our free service
  • I Love Narcissistic Numbers
  • Atheists Need To Leave Christmas Alone, Do They?
  • Understanding Evolution

Recent Comments

glennwestmore on I Love Narcissistic Numbe…
humanistfox on Understanding Evolution
Louis Barbe on I Love Narcissistic Numbe…
masondan on Are Men And Women Equal?
theirishatheist on Definitive Proof Of God’…

Categories

  • computing
  • crime
  • drums and drumming
  • finance
  • mathematics
  • politics
  • religion
  • science
  • telly
  • war

Meta

  • Register
  • Log in
  • Entries feed
  • Comments feed
  • WordPress.com

Tags

acupuncunturist all nudey atheism atheist baldies ballybgicken ballybricken blackberries blackberry class classy delilah deluded deranged dragged the balls drumming drums existence existentialism Father O'Connor fun gender get rich quick god goolies inflatable hammer Jojo Jojo Mayer knife language laughing lazy Llangollen man mansion math mathematics maths men miley cyrus monotheism MTV narcissistic numbers number numbers P45 panties proof proof of god recreational mathematics religion scrap sex sexism sexist willies short hair sinead o'connor skinheads smug Dermot snot song suicidal sympathetic talentless The fucking journey theism twerping utter horseshit Wales waterford wine witless woman women xfactor

Archives

Enter your email address to follow this blog and receive notifications of new posts by email.

Follow me on Twitter

My Tweets

Create a free website or blog at WordPress.com.

Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Cookie Policy
  • Follow Following
    • Metazz
    • Already have a WordPress.com account? Log in now.
    • Metazz
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar