banner



What Is Magic Number in Java Programming

Before looking at the Magic number in Java, let's gets some basic understanding on a Magic number

What is a Magic Number?

A Magic Number is a text or numeric value which is used in the code which is used for some identification. Using such constant can help us distinguish the files among the many other file formats.

Say for example,

  • PDF Files will start with the magic text %PDF –> Hex (25 50 44 46)
  • PNG Files will start with the magic text %PNG –> Hex (25 50 4E 47)
  • Java class Files will start with the magic text Êþº¾ –> Hex (CAFEBABE)

What is a Magic Number in programming?

I got two different answers for a magic number in programming, let's take a look into the code for both of them.

Program 1: Ramanujan Number or Taxicab Number

A Magic Number is a number which is equal to the product of the sum of all digits of a number and reverse of the sum. This is also known as Ramanujan Number or Taxicab Number. For Example, 1729 is a Magic Number. Sum of all digits is 19, the reverse of the Sum is 91, and Product of these numbers 19 * 91 is equal to the original number (19 * 91 = 1729). In this program, let's print the Ramanujan Number

Magic Number in Java

  • Get the input number from the user
  • Calculate the sum of the individual digits
  • Find the reverse of the sum of digits
  • Multiply both sum and reverse, If the product is the same as the original number then it is a Magic Number
package com.javainterviewpoint;  import java.util.Scanner;  public class MagicNumber {     public static void main(String[] args)     {         System.out.println("Enter any number to check : ");             Scanner scanner = new Scanner(System.in);         int originalNumber = scanner.nextInt();                           int sum = calculateSum(originalNumber);         int reverseSum = findReverse(sum);                  if( (sum * reverseSum) == originalNumber)             System.out.println(originalNumber +" is a Magic Number");         else             System.out.println(originalNumber +" is not a Magic Number");     }          public static int calculateSum(int number)     {         int sum = 0;         while (number > 0)         {             sum = sum + number % 10;             number = number / 10;         }         return sum;     }     public static int findReverse(int number)     {         int reverse = 0;         while (number > 0)         {             int digit = number % 10;             reverse = reverse * 10 + digit;             number = number / 10;         }         return reverse;     } }

originalNumber hold the input number entered by the user

Calculate the Sum of each digit

The calculateSum() calculates the sum of all individual digits, while loop continues to run until the number is greater than zero.

First Iteration

At the start, number is 1729 and sum is 0, while (1729 > 0) is TRUE, now inside the while loop

sum = sum + number % 10 ( sum = 0 + 9), now sum is 9

Now we need to remove the last digit from the number, so we need to divide the number by 10 and so now number = 172

Second Iteration

The value of both number and sum are changed [number = 172 and sum = 9], while (172 > 0) is TRUE, so the execution continues into the while loop

sum = (9 + 172 % 10) —> sum = 11

Now remove the last digit from the number,

number  =  (number / 10)  —> number = (172 / 10) —> number = 17

Third Iteration

Now number is 17 and sum is 11, while (17 > 0) is TRUE

sum = (11 + 17 % 10) —> sum = 18

number = (17 / 10) —> number = 1

Fourth Iteration

Now number is 1 and sum is 18, while (1 > 0) is TRUE

sum = 18 + 1 % 10 —> sum = 19

number = 1 / 10 —> number = 0

Fifth Iteration fails as the number is now zero.

Find the reverse of sum

Now need to calculate the reverse of the sum, the findReverse() method calculates the reverse of the sum, here also the loop continues to executes until the value is not zero

First Iteration

number is 19 and reverse is 0, while( 19 > 0) is TRUE

digit = number % 10 (digit = 19 % 10), now digit is 9

reverse = reverse * 10 + digit (reverse = 0 + 9), now reverse is 9

Remove the last digit from the number, so we need to divide the number by 10 and so now number = 1

Second Iteration

Now number is 1 and reverse is 9, while( 1 > 0) is TRUE

digit = 1 % 10 —> digit = 1

reverse = 9 *10 + 1 —> reverse = 91

number = 1 / 10 —> number = 0

Third Iteration fails as the value of the number is zero.

Finally, calculate the product of sum and reverseSum, and check if it is equal to the original number.

Output:

Enter any number to check :  1854 1854 is not a Magic Number Enter any number to check :  1729 1729 is a Magic Number

Java Program to Find Magic Numbers between 1 and 10000

Let's now take a look into the program which prints all the Magic Numbers within the range of 1 to 10000

package com.javainterviewpoint;  public class MagicNumber { 	public static void main(String[] args) 	{ 		int i = 1; 		System.out.println("*** List of Magic Numbers between 1 to 10000 ***"); 		while (i <= 10000) 		{ 			int sum = calculateSum(i); 			int reverseSum = findReverse(sum); 			if ((sum * reverseSum) == i) 				System.out.println(i); 			i++; 		} 	}  	public static int calculateSum(int number) 	{ 		int sum = 0; 		while (number > 0) 		{ 			sum = sum + number % 10; 			number = number / 10; 		} 		return sum; 	}  	public static int findReverse(int number) 	{ 		int reverse = 0; 		while (number > 0) 		{ 			int digit = number % 10; 			reverse = reverse * 10 + digit; 			number = number / 10; 		} 		return reverse; 	} }

Output:

*** List of Magic Numbers between 1 to 10000 *** 1 81 1458 1729

Program 2:

In this type, when the sum of all digits recursively added till the sum is a single digit, if the sum is equal to 1 then the number is a magic number.

For Example, 1234 is a magic number because the recursive sum of digits is 1

1 + 2 + 3 + 4 = 10 [10 is not a single digit, and hence we need to continue with the adding the digits again]

1 + 0 = 1   [Sum is now 1 and it is a single-digit]

package com.javainterviewpoint;  import java.util.Scanner;  public class MagicNumber { 	public static void main(String[] args) 	{ 		System.out.println("Enter any number to check : "); 		Scanner scanner = new Scanner(System.in); 		int number = scanner.nextInt();  		if(checkMagicNumber(number)) 			System.out.println(number +" is a Magic Number"); 		else 			System.out.println(number +" is not a Magic Number"); 	}  	public static boolean checkMagicNumber(int number) 	{ 		int sum = 0; 		while (number > 0 || sum > 9) 		{ 			if (number == 0) 			{ 				number = sum; 				sum = 0; 			} 			sum = sum + number % 10; 			number = number / 10; 		} 		 		if(sum == 1) 			return true; 		else 			return false; 	} }

A simple tip for this approach is all the multiples of 9 + 1 will be a magic number.

1, 10, 19, 28, 37, 46, 55 …. so on..

We can re-write the above code simply like below

package com.javainterviewpoint;  import java.util.Scanner;  public class MagicNumber { 	public static void main(String[] args) 	{ 		System.out.println("Enter any number to check : "); 		Scanner scanner = new Scanner(System.in); 		int number = scanner.nextInt();  		if(checkMagicNumber(number)) 			System.out.println(number +" is a Magic Number"); 		else 			System.out.println(number +" is not a Magic Number"); 	}  	public static boolean checkMagicNumber(int number) 	{ 		//if( ( ((number / 9)*9) +1 ) == number) 			 		//if( number % 9 == 1) 		 		if( ((number - 1) % 9) == 0) 			return true; 		else 			return false; 	} }

Bonus

Why is CAFEBABE Java's Magic Word?

Explanation from James Gosling

"We used to go to lunch at a place called St Michael's Alley. According to local legend, in the deep dark past, the Grateful Dead used to perform there before they made it big. It was a pretty funky place that was definitely a Grateful Dead Kinda Place.

When Jerry died, they even put up a little Buddhist shrine. When we used to go there, we referred to the place as Cafe Dead. Somewhere along the line, it was noticed that this was a HEX number.

I was re-vamping some file format code and needed a couple of magic numbers: one for the persistent object file, and one for classes. I used CAFEDEAD for the object file format, and in grepping for 4 character hex words that fit after "CAFE" (it seemed to be a good theme) I hit on BABE and decided to use it.

At that time, it didn't seem terribly important or destined to go anywhere but the trash-can of history. So CAFEBABE became the class file format, and CAFEDEAD was the persistent object format. But the persistent object facility went away, and along with it went the use of CAFEDEAD – it was eventually replaced by RMI.

Wikipedia

What Is Magic Number in Java Programming

Source: https://www.javainterviewpoint.com/magic-number-in-java/

0 Response to "What Is Magic Number in Java Programming"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel