user9116881
user9116881

Reputation: 1

Dividing until a certain number is reached and storing how many times the loop divided

If you divide 1 by 2, you get 0.5. If you divide it again by 2, you get 0.25. Write a program that calculates and outputs the number of times you have to divide 1 by 2 to get a value less than one ten-thousandth (0.0001).

I have a for loop that should be working but its not returning any results

public class Main {

public static void main(String[] args) {
    double count ;
    for(double i = 1; i<= 0.0001; count++){
            count = i/2;


        System.out.println("You have to divide 1 " + count + "times to get 0.0001");


    }

The program runs it just doesn't return anything.

Upvotes: 0

Views: 2570

Answers (4)

Radagast81
Radagast81

Reputation: 3016

You can translate your equation:

x / y^n <= z

to

n >= log(x/z) / log(y)

And therefore it's simply:

public static void main(String[] args) {
   System.out.println("You have to divide 1 " + Math.ceil(Math.log(1.0 / 0.0001) / Math.log(2)) + " times by 2 to get 0.0001");
}

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44854

Try this

    int count = 0;
    double i = 1;
    while(i >= 0.0001){
            i = i/2;
            count++;
            System.out.println("You have to divide 1 " + count + " times to get 0.0001");
    }

Probably you only want to print out after the loop

Before the value of count was never being used to evaluate the loop. Try having two variables.

Upvotes: 2

vaibhav shanker
vaibhav shanker

Reputation: 173

You could use below code .

        int count = 0;
        for(double i = 1; i>= 0.0001; ){
                i = i/2;
           count++;

            System.out.println("You have to divide 1 " + count + " times to get " + i);


        }

Upvotes: 0

user9116881
user9116881

Reputation: 1

Ok I got it just had to switch some things around public class Main {

public static void main(String[] args) {

    int count = 0;
    for (double i = 1; i >= 0.0001; count++ ) {
             i = i / 2;



    }
    System.out.println("You have to divide 1 " + count + " times to get 0.0001");

Upvotes: 0

Related Questions