Numbers have different representations depending on the bases on which they are expressed. For example in base 3, the number 12 is written as 110 (1 x 32 + 1 x 31 + 0 x 30), but in base 8 it is written as 14(1 x 81 + 4 x 80).
Consider, for example, the integers 12 and 5. Certainly these are 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 base 6 or 5 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 calculate 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.
Test your program for the following data and some random data:
The logic is quite simple just imput two integers, starting from base 1 find its value and compare it
with the value of the second number from bases 1 to 20 (minus the base of first number).
Look for equality and print!
import java.util.*;
public class ISC2004Q2 {
public static void main(String[] args) {
int X,Y;
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of X:");
X = in.nextInt();
System.out.println("Enter the value of Y:");
Y = in.nextInt();
Base obj = new Base(X,Y);
obj.display();
in.close();
}
}
class Base {
public void display() {
for(int i=1;i<=20;i++) {
for(int j=1;j<=20;j++) {
if(baseRepresentation(X,i)==baseRepresentation(Y,j) && i!=j) {
flag=true;
System.out.println(X+" in
base "+i+" equals "+Y+" in base "+j);
break;
}
if(flag==true)
break;
}
}
if(!flag)
System.out.println("NEVER EQUAL IN ANY BASE LESS THAN 20");
}
private int baseRepresentation(int numb,int b) {
int tmp=0,j=0,N=numb;
do {
tmp=tmp+(N%10)*(int)Math.pow(b, j);
j++;
N /=10;
}while(N>=1);
return tmp;
}
Base(int X,int Y){
this.X=X;
this.Y=Y;
flag=false;
}
private boolean flag;
private int X;
private int Y;
}
No comments:
Post a Comment