user2817797
user2817797

Reputation: 7

Solving elimination using nested loops in java?

I was trying to solve a program challenge that solves this prompt "When 2, 3, 4, 5, 6 eggs are removed at a time from a basket of eggs, the remaining amounts are 1, 2, 3, 4,5 eggs respectively. When 7 eggs are removed at a time, no eggs remain. What is the least number of eggs I could have had in the basket?"

I tried to make a program using nested loops and I feel like it should work, but when I run the program, it just prints blank space. I never get a number to satisfy the equation. Can someone help me, or show me what I did wrong please?

I'm only allowed to use nested loops and decision statements.

public class Program{ 

public static void main (String []args){

  int c,d,e,f,g,h;

for (int j=1; j<1000; j++){

    for (c=j; c>=1; c=c-2){
    }


        if (c==1){
            for (d=j; d>=2; d=d-3){
            }

        if (d==2){
            for (e=j; e>=3; e=e-4){
            }  
        if (e==3){
            for (f=j; f>=4; f=f-5){
            }
        if (f==4){
            for (g=j; g>=5; g=g-6){
            }
        if (g==5){
            for (h=j; g>=0; h=h-7){
            }
        if (h==0){
            System.out.println(+j);   
        }
        }
        }
        }
        }
        }
} 
}
}

Upvotes: 0

Views: 362

Answers (2)

Christian Tapia
Christian Tapia

Reputation: 34146

Try this:

public static void main(String[] args) {
    int x = 7;
    int result = -1;
    while (true) {
        if ((x % 2 == 1) && (x % 3 == 2) && (x % 4 == 3) && (x % 5 == 4)
                && (x % 6 == 5)) {
            result = x;
            break;
        }
        x += 7; // This because you know its multiple of 7
    }
    System.out.println("Result is: " + result);
}

Upvotes: 1

John
John

Reputation: 16007

int numberOfEggs = 0;
for (;;)
{
    if (numberOfEggs % 2 == 1 &&
        numberOfEggs % 3 == 2 &&
        numberOfEggs % 4 == 3 &&
        numberOfEggs % 5 == 4 &&
        numberOfEggs % 6 == 5   )
        return numberOfEggs;
    else
        numberOfEggs += 7;
}

Upvotes: 1

Related Questions