Finding integers that are divisible by 6 or 7 but not both
-
20-08-2019 - |
Question
I am trying to write a program that displays the integers between 1 and 100 that are divisible by either 6 or 7 but not both.
Here is my code:
import acm.program.*;
public class Problem4 extends ConsoleProgram
{
public void run()
{
for (int i = 1; i <= 100; i++)
{
boolean num = ((i % 6 == 0) || (i % 7 == 0));
if (num == true)
println(i + " is divisible");
}
}
}
The above code shows the following answers: 6,7,12,14,18,21,24,28,30,35,36,42,48,49,54,56,60,63,66,70,72,77,78,84,90,91,96,98
Now the bold numbers 42 and 84 are both divisbile by 6 and 7. Now If I change the ||
to &&
in the above code, the result shows only 42 and 84.
What change should I do to remove these 2 numbers from the final result?
Solution
you have to make your condition look like:
boolean num = (i % 6 == 0 || i % 7 == 0) && !(i % 6 == 0 && i % 7 == 0);
that's basically converting "but not both" to Java code :)
OTHER TIPS
XOR is the way to go.
import acm.program.*;
public class Problem4 extends ConsoleProgram {
public void run() {
for (int i = 1; i <= 100; i++) {
if ( (i % 6 == 0) ^ (i % 7 == 0) ) {
println(i + " is divisible");
}
}
}
}
You need an extra check for "but not both". I think it should be:
boolean num = ((i % 6 == 0) || (i % 7 == 0)) && (i % 42 != 0);
you can also try
boolean num = ((i % 6 == 0) != (i % 7 == 0));
Think about what it means to be divisible by 6 and 7... the answer to life the universe and everything.
import acm.program.*;
public class Problem4 extends ConsoleProgram
{
public void run()
{
for (int i = 1; i <= 100; i++)
{
boolean num = ((i % 6 == 0) || (i % 7 == 0));
boolean both = ((i % 6 == 0) && (i % 7 == 0));
if ((num == true) && (both == false))
println(i + " is divisible");
}
}
}
Here is a snippet that should work as well- in C++ but change to boolean...
int value;
if ((value % 6 == 0 && value % 7 != 0) || (value % 6 != 0 && value % 7 == 0))
cout << "Is " << value << " divisible by 6 or 7, but not both? true" << endl;
else
cout << "Is " << value << " divisible by 6 or 7, but not both? false" << endl;
A little simplified version
for(int i=1; i<=100; i++) {
// Either Divisible by 6 or 7 but not both
if((i%6==0 && i%7!=0) ||( i%7==0 && i%6!=0)) {
println(i);