Simplify multiple similar statements on (while) - java

For example let's say i have this:
while( i1 % 1!=0 || i1 % 2!=0 || i1 % 11!=0 || i1 % 16!=0 ||
i1 % 7!=0 ||i1 % 3!=0 ||i1 % 12!=0 ||i1 % 17!=0 ||
i1 % 8!=0 ||i1 % 4!=0 ||i1 % 13!=0 ||i1 % 18!=0 ||
i1 % 9!=0 ||i1 % 5!=0 ||i1 % 14!=0 ||i1 % 19!=0 ||
i1 % 10!=0 ||i1 % 6!=0 ||i1 % 15!=0 ||i1 % 20!=0 ) {}
How can i simplify that?
Like while the module of i1 for 1-20 is different to 0. without all that mess.
Pardon if its a dumb question, I'm fairly new to this.

You can create a method that will generate the statement for you, and using a forloop to iterate 20 numbers and check if the modulo of each number is not equal to zero.
sample:
public boolean checkModulos(int toCheck)
{
for(int i = 0; i < 20; i++)
{
if(toCheck % i != 0)
return true;
}
return false;
}
to use it is:
while(checkModulos(i1))

You can work with the statement a bit. With DeMorgan's Law (!A || !B == !(A &&B)), you can turn it into !(i1 % 1 == 0 && i1 % 2 == 0 ... && i1 % 20 == 0)
Now think about the statement a bit. A number mod another equaling zero means the first number is divisible by the second. That means the statement really reads: not (i1 is divisible by all the numbers 1-20). So find a number n that is divisible by all the numbers 1-20, and have the loop become while( !(i1 % n == 0) ), or just while(i1 % n != 0)

Related

Either ints in range in one "if" statement

Maybe I am swatting flies with a sledgehammer but...
I was doing this exerice on CodingBat;
Given 2 ints, a and b, return their sum. However, "teen" values in the range [13, 19] are extra lucky. So if either value is a teen, just return 19.
and this is the answer I came up with;
public int teenSum(int a, int b)
{
if (a >= 13 && a <= 19) return 19;
if (b >= 13 && b <= 19) return 19;
else return a + b;
}
I was wondering if there was a way to solve this problem in just one "if" statement... is there?
If you use a ternary operator (? :) you could do it with zero if statements. Something like,
public int teenSum(int a, int b)
{
return (a > 12 && a < 20) || (b > 12 && b < 20) ? 19 : a + b;
}
You can have a logically equivalent expression using logical OR:
if ((a >= 13 && a <= 19) || (b >= 13 && b <= 19)) return 19;
Sure. By putting two if statements as guard clauses, what you're really doing is a logical OR. So:
if ((a >= 13 && a <= 19) || (b >= 13 && b <= 19)) return 19;
would also work.
By the way, the else is redundant.
You can do it entirely without if statements, using the ?: ternary operator.
return (a >= 13 && a <= 19) || (b >= 13 && b <= 19) ? 19 : a + b;

Java: How to test if individual characters are even or odd? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
In Java, how do I test if a character is an even or odd digit?
Here is what I have so far:
import java.util.Scanner;
public class OddOrEven{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int number, digit1, digit2, digit3;
System.out.print( "Enter three-digit number: " );// prompt
number = input.nextInt(); // read number
// determine the 3 digits
digit1 = number / 100;
digit2 = number % 100 / 10;
digit3 = number % 100 % 10;
if (digit1 % 2 == 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println( "This number contains all even digits.");
if (digit1 % 2 != 0 && digit2 % 2 == 0 && digit3 % 2 == 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 == 0 );
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 == 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains both odd and even digits.");
if (digit1 % 2 != 0 && digit2 % 2 != 0 && digit3 % 2 != 0);
System.out.println("This number contains all odd digits.");
}
}
If the number you are working with is an int (or a similar primitive type like long) then you can do something like this
int num = // something
while (num != 0) {
int digit = num % 10;
System.out.println(digit + " is " + (digit % 2 == 0 ? "even" : "odd"));
num /= 10;
}
This will iterate over the digits from right to left.
public static void main(String[] args) throws Exception {
int num = 28172;
String temp = Integer.toString(num);
int[] numArray = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
numArray[i] = temp.charAt(i) - '0';
}
for (int i : numArray) {
System.out.println("Num " + i + " is " + ((i % 2 == 0) ? "even" : "odd"));
}
}
Gives me the output:
Num 2 is even
Num 8 is even
Num 1 is odd
Num 7 is odd
Num 2 is even
First, convert the int to a String. Then, since Strings are Character arrays, you can loop through each character in the array and turn it into an Integer by subtracting the ascii Character 0. Then, you can loop through each Integer in this array, and use the mod operator (%) which will give you the remainder of a division. num%2==0 will return true if the number is even, otherwise false.

How does Java evaluate this statement?

I have this expression in the if else statement
if (row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1) {
return 0;
}
else {
return 1;
}
which behaves as intended, returning 0 when the row and column are either both even or both odd. What perplexes me is how Java didn't read it as
(row % 2 == 0 && (col % 2 == 0 || row % 2 == 1 && col % 2 == 1))
How exactly does Java evaluate a statement without parenthesis?
How exactly does Java read a statement without parenthesis?
By applying the operator precedence rules. The Java language specification says that && has a higher precedence than ||, and that means that:
row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1
is equivalent to:
(row % 2 == 0 && col % 2 == 0) || (row % 2 == 1 && col % 2 == 1)
And in fact, == has a higher precedence than &&, so that is equivalent to:
((row % 2 == 0) && (col % 2 == 0)) || ((row % 2 == 1) && (col % 2 == 1))
This page from the Java Tutorial provides more information on operator precedence and how it affects expression evaluation.
For what it is worth, there is a natural parallel between operator precedence in a programming language and the meaning of simple arithmetical expressions ... as you were taught in primary school. For example, you were taught that 1 + 2 x 3 means the same thing as 1 + (2 x 3); i.e. the answer is 7 and not 9. In technical terms, the x (multiplication) operator has higher precedence than the + (addition) operator.
The idea is the same in a typical programming language, except that there is a larger range of operators to deal with ... and the rules are (generally speaking) more precisely specified1.
1 - For instance, since the evaluation of primaries and operators can in some cases have side effects, it can be important to know the precise order in which the sub expressions get evaluated.
That is because of the precedence order. && has precedence over ||.
Look here.

How to check if an integer can be divided by 3

How to check if my integer can be divided by 3 as below:
for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
Use the modulo operator.
if(i % 3 == 0)
Also see Modulo operation at Wikipedia
If you are using a loop, you can use the fact that every third number can be divided by 3.
for(int i = 0; i < 24; i += 3) {
System.out.println(i + " can be divided by 3");
System.out.println((i+1) + " cannot be divided by 3");
System.out.println((i+2) + " cannnot be divided by 3");
}
This avoids the need for a modulo and cuts the number of loops by a factor of 3.
Use the MOD operator
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
Well, what you could do (it might be a bit faster; it is faster on my machine) is:
boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
instead of
boolean canBeDevidedBy3 = (i % 3) == 0;
However, the multiplication trick only works for -2 <= i <= 1610612735. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0. It's so much simpler, and will always work.
Check the remainder of i devided by 3
if (i % 3 == 0) {}
inside the loop:
if (i%3 == 0)
// it can be divided by 3
% is called "mod" or "modulus" and gives you the remainder when dividing two numbers.
These are all true:
6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
if( i % 3 == 0 ){
System.out.println("can be divided by 3");
}else{
System.out.println("cant divide by 3");
}
Is this question for real?

simple boolean question

What am I doing wrong here?
I am wanting to display integers from 1-100 who are divisible by either 6 or 7. That's done and working. The next step is to not display any that are divisible by both...that isn't working in my loop (those integers are still displaying)
for (int i = 1; i < 100; i++)
if (i % 6 == 0 || i % 7 == 0 && i % (6 * 7) != 0){
println(i);
}
Thanks!
Joel
try making your condition more explicit by adding (...), like so:
if (((i % 6 == 0 || i % 7 == 0) && (i % (6 * 7) != 0)) {
}
by default && takes precedence over ||
Missing parentheses:
for (int i = 1; i < 100; i++) {
if ((i % 6 == 0 || i % 7 == 0) && i % (6 * 7) != 0) {
println(i);
}
}
You could also use the exclusive or
for (int i = 1; i < 100; i++) {
if ((i % 6 == 0) ^ (i % 7 == 0)) {
println(i);
}
}
or just an unequal if ((i % 6 == 0) != (i % 7 == 0))
Since exclusive or is not used that often, I doubt this will increase the readability of the code...
I would simply stop worrying about how to evaluate precedence, and use something like:
for (int i = 1; i <= 100; i++) {
if ((i % 42) == 0) continue;
if ((i % 6) == 0) println (i);
if ((i % 7) == 0) println (i);
}
I'm assuming here that 1-100 was an inclusive range in which case you should use <= rather than <. It won't matter for your specific case since 100 is divisible by neither 6 nor 7.
Guess what? Any decent optimising compiler (including JIT ones) will probably end up generating the same code as for all the other possibilities. And, even if it didn't, it wouldn't matter unless you were calling this function a great many times.
I think that's a tiny bit more readable than:
if (i % 6 == 0 || i % 7 == 0 && i % (6 * 7) != 0) ...
or, worse yet, the Lisp-like thing you'll have to turn it into to get it working properly :-)
Keep in mind one possibility - you can change your loop to make it more efficient (sevenfold), for the specific case with 6 and 7, thus:
for (int i = 7; i <= 100; i += 7)
if ((i % 6) != 0)
println (i);
This uses the for loop itself to only check multiples of 7 and print them if they're not also multiples of 6.
for (int i = 1; i < 100; i++)
if ((i % 6 == 0 || i % 7 == 0) && !(i % 6 == 0 && i % 7 == 0)){
println(i);
}

Categories

Resources