Reputation: 41
I need to write a code that finds the smallest integer whose remainder is:
• 1 when divided by 3
• 2 when divided by 5
• 3 when divided by 7
I tried the following code but my output is 1. I tried changing the initial value but it would still just output the initial value.
public static void main (String[] args)
{
int i=2;
while((i%3)!=1 && (i%5)!=2 && (i%7)!=3) {
i++;
}
System.out.print(i);
}
Upvotes: 1
Views: 89
Reputation: 5754
The logic you have in the while loop isn't correct, and it's difficult to see the problem due to how it's written. Instead of fixing that and trying to convince you that it's correct, here's a different approach that's broken out into separate pieces so it should be easier to reason about. It works by flipping the loop around a little bit: run forever until a specific condition is met.
int i = 2;
while (true) {
boolean correctRemainderFor3 = (i % 3 == 1);
boolean correctRemainderFor5 = (i % 5 == 2);
boolean correctRemainderFor7 = (i % 7 == 3);
if (correctRemainderFor3 && correctRemainderFor5 && correctRemainderFor7) {
break;
} else {
i++;
}
}
System.out.print(i);
When I run the above code locally, it prints out 52
.
Upvotes: 1
Reputation: 9509
Your condition within while
loop is not correct, it should be:
while((i%3)!=1 || (i%5)!=2 || (i%7)!=3)
Why?
You need to find the first number for which applies:
a%3 == 1 and a%5 == 2 and a%7 == 3
in order to do that you need to skip all numbers where:
not(a%3 == 1 and a%5 == 2 and a%7 == 3)
If you apply De Morgan's laws you get:
a%3 != 1 or a%5 != 2 or a%7 != 3
Upvotes: 1