Search code examples
javamathdivisionlogarithm

Simulating Logarithms by repeated Integer division


I'm trying to write a program that simulates logarithms by repeated integer division. A user inputs a base number and a value X that they want to take the log of. The code runs through a loop and increments a count after each successive division. The code is set to stop after the value of X gets smaller than the base because I'm only using int type variables.

This code works fine for some numbers and bases but for others it gives the wrong value. It does " log_2(64) is 6 " however it doesn't do log_10 of 100. It gives a count of 10.

public static void main(String[] args) {

    Scanner inScan = new Scanner(System.in);

    int base;
    int X;
    int response;
    int n=0;

  do{   
    System.out.println("Java Lab 3 Logarithm Solver.");
    System.out.println("Please enter a base > 1");
    base = inScan.nextInt();
    System.out.println("Please enter a number, X>0.");
    X = inScan.nextInt();
    if (X > 0 && base > 1){
        System.out.println("Logarithm base " +base+ " of " +X+" is ");
         for ( ; X>base ;n++){

            X=(X/base);
        }
        System.out.println(n);
    } else {
        System.out.println("Invalide numbers.");
    } 
        System.out.println("Would you like to go again? Press 1, press 0 to quit");
        response = inScan.nextInt(); 

  } while (response == 1);

 }
}

Solution

  • You are declaring n as a global variable; I suspect that if you check your tests, this algorithm works only the first time through every time you compile and run it. Instead of having n as global, declare it in your for loop like

    for(int n = 0; X < base; n++)
    

    since it looks like you need the value of n later, I suggest having a variable with a wider scope, perhaps declared in the do-while loop, to store the n in, like

    do
    { 
        int numberOfTimesThroughLoop = 0;
        ...
        for(...)
        {
            x = x/base;
            numberOfTimesThroughLoop = n;
        }
    }
    

    as a side note, most of the time variables (even single letter variable, like your 'X') being with a lower case character