Ticker

6/recent/ticker-posts

Program in JAVA to calculate the smallest base for which 2 numbers are equal

Question: Write a program in java to input 2 integers x and y and calculate the smallest base for x and smallest base for y so that x and y represent the same value between base 1 and 20. The alphabetic characters A through J represent digits 10 through 19.

Code:



import java.io.*;

public class correct_base {
    public static void main(String args[]) throws IOException {

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter x=");
        String n1 = in.readLine();// accepting first number
        System.out.print("Enter y=");
        String n2 = in.readLine();// accepting second number
        int l1 = n1.length();
        int l2 = n2.length();
        int k1 = 0dec1 = 0t = 1k2 = 0dec2 = 0;// Initialising variables
        for (int a = 2a <= 20a++, dec1 = 0k1 = 0)// loop for checking bases of first number
        {
            for (int i = l1 - 1i >= 0i--, k1++) {
                if (Character.isLetter(n1.charAt(i)) == true)
                    dec1 += Math.pow(ak1) * ((n1.charAt(i)) - 55);// converting base'a' to base 10
                else
                    dec1 += Math.pow(ak1) * ((n1.charAt(i)) - 48);// converting base'a' to base 10
            }
            for (int b = 2b <= 20b++, dec2 = 0k2 = 0)// loop for checking bases of second number
            {
                for (int j = l2 - 1j >= 0j--, k2++) {
                    if (Character.isLetter(n2.charAt(j)) == true)
                        dec2 += Math.pow(bk2) * ((n2.charAt(j)) - 55);// converting base'b' to base 10
                    else
                        dec2 += Math.pow(bk2) * ((n2.charAt(j)) - 48);// converting base'b' to base 10
                }
                if (dec1 == dec2 && a != b)// checking for equality of both numbers
                {
                    if (l2 == 1 && Character.isLetter(n2.charAt(0)) == true)
                        b = n2.charAt(0) - 54;
                    else if (l2 == 1)
                        b = n2.charAt(0) - 47;
                    if (l1 == 1 && Character.isLetter(n1.charAt(0)) == true)
                        a = n1.charAt(0) - 54;
                    else if (l1 == 1)
                        a = n1.charAt(0) - 47;
                    System.out.println(n1 + "(base" + a + ")=" + n2 + "(base" + b + ")");// Displaying correct bases
                    t = 0;
                    break;
                }
            }
            if (t == 0)
                break;
        }
        if (t == 1)// checking that numbers are equal in any base between 2 to 20
            System.out.println(n1 + " is not equal to " + n2 + " in any base between 2 to 20");
    }
}


Output Window:


Post a Comment

0 Comments