Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can someone explain the steps to compute this equation? Java

Write a program that computes the following equation. 100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100

I am not asking for a solution. Yes this is a homework problem, but I am not here to copy paste the answers. I asked my professor to explain the problem or how should I approach this problem? She said "I can't tell you anything."

public static void main(String[] args){
    int i;

    for(i = 100; i >= 1; i--)
    {
        int result = i/j;
        j = j+1;
        System.out.println(result);
    }
}
like image 293
happy face Avatar asked Mar 04 '26 06:03

happy face


2 Answers

You can try to observe a "trend" or "pattern" when solving questions of this type.

Given: 100/1+99/2+98/3+97/4+96/5...3/98+2/99+1/100

We derived: Numerator/Denominator, let's call it n divide by d (n/d)

Pattern Observed:

  • n - 1 after every loop
  • d + 1 after every loop

So, if you have 100 numbers, you need to loop 100 times. Thus using a for-loop which loops 100 times will seemed appropriate:

for(int n=0; n<100; n++) //A loop which loops 100 times from 0 - 100

To let n start with 100, we change the loop a little to let n start from 100 instead of 0:

for(int n=100; n>0; n--) //A loop which loops 100 times from 100 - 0

You settled n, now d needs to start from 1.

int d = 1; //declare outside the loop

Putting everything together, you get:

int d = 1;
double result = 0.0;
for (int n=100; n>0; x--)
{
    result += (double)n/d; //Cast either n or d to double, to prevent loss of precision
    d ++; //add 1 to d after every loop
}
like image 107
user3437460 Avatar answered Mar 05 '26 20:03

user3437460


You are on the right track. You need to loop like you've done, but then you need to SUM up all the results. In your example you can try:

result = result + i/j;

or

result += i/j;

Note that the declaration of result needs to be outside the loop otherwise you are always initializing it.
Also think about the division (hint), you are dividing integers...

like image 44
Alvin Bunk Avatar answered Mar 05 '26 20:03

Alvin Bunk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!