Number have different representations depending on the bases on which they are expressed. For example in base 3, the number 12 is written as 110 , but in base 8 it is written as
Consider, for example, the integers 12 and 5. Certainly these ar not equal if base 10 is used for each, but suppose 12 was a base 3 number and 5 was a base 6 number then what happens.
12 base 3 = 1 x 31 + 2 x 30, or 5 was base 10(5 in any base is equal to 5 base 10).
So 12 and 5 can be equal if you select the right bases for each of them/
Write a program to input two integers, X and Y and calculated the smallest base for X and smallest base for Y (likely different from X) so that X and Y represent the same value. The base associated with X and Y will be between 1 and 20 (both inclusive), in representing these numbers the digits 0 to 9 have their usual decimal interpretations. The uppercase alphabetic characters A through J represent digits 10 through 19 respectively.
Test your program for the following data and some random data:
INPUT : | |
X = 12, Y = 5 | |
OUTPUT: | |
12(base 3) = 5(base 6) | |
INPUT : | |
X = 10, Y = A | |
OUTPUT: | |
10(base 10) = A(base 11) | |
INPUT : | |
X = 123, Y = 456 | |
OUTPUT: | |
123 is not equal to 456 in any base between 2 to 20 | |
INPUT : | |
X = 42, Y = 36 | |
OUTPUT: | |
42(base 7) = 36(base 8) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
import java.util.*; public class Base_Equality { String dg = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int base2dec(String n, int b) { int i, l = n.length(), d=0, x, c=0; for(i = l-1; i>=0; i--) { //Converting the number to decimal from base b x = dg.indexOf(n.charAt(i)); if(b<=x) //If any digit is greater than or equal to the base then the number cannot be from that base return -1; d = d + x*(int)Math.pow(b, c); c++; } return d; } void check(String a, String b) { int i, j, m, n; for(i=2;i<=20;i++) { m = base2dec(a, i); if(m==-1) //Skipping the loop continue; for(j=2;j<=20;j++) { n = base2dec(b, j); if(n==-1) //Skipping the loop continue; if(m == n) { System.out.println(a+" in base "+i+" and "+b+" in base "+j+" are equal"); System.exit(0); } } } System.out.println(a+" is not equal to "+b+" in any base between 2 to 20"); } public static void main() { Scanner sc = new Scanner(System.in); String a, b; Base_Equality ob = new Base_Equality(); System.out.println("Enter 2 numbers: "); a = sc.nextLine(); //Taking input b = sc.nextLine(); ob.check(a, b); //Calling the function } } |
Output 1
Output 2
Leave a Reply
You must be logged in to post a comment.