Boolean expression (x / 2) * 2 == x to test [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This is actually one of my lab questions.
You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. With each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even
and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
I basically know what this question requires me to do. However, I don’t quite understand why boolean expression, (x/2)*2 == x, can test whether the integer is an ever number or an odd number. Lets say my number is 59, which is an odd integer obviously. 59 divided by 2 is 29.5. 29.5 times 2, which equals 59. No matter what x is, (x/2)*2 always equals x. So how to make this expression false when the integer is an odd. Then I can determine what I should print.

Because you're dealing with integers, there's always a rounding down to the nearest round number.
59/2 = 29 when all elements are integers.
Multiplying the result by 2 gives 58, so since the 2 numbers aren't the same, we deduce that the number, 59, is odd.

This should be your code written in a beginners way, if u still don't understand something just ask. The formula x==(x/2)*2 is used because when you are dividing two integer variables the result is always a round number, which later if it's odd, won't give u the same initial number. (59/2=29 => 29*2=58 => false)...
import java.util.*;
public class EvenOrOdd{
public static void main( String [] args){
Scanner scan=new Scanner(System.in);
boolean result=true;
List<Integer> EvenNums = new ArrayList<Integer>();
List<Integer> OddNums = new ArrayList<Integer>();
for(int i=0; i<5; i++){
System.out.println("Enter a number: ");
int x=scan.nextInt();
if(x==(x/2)*2){
result=true;
System.out.println(result);
EvenNums.add(x);
continue;
}else if(x!=(x/2)*2){
result=false;
System.out.println(result);
OddNums.add(x);
continue;
}
}
System.out.println("Done");
System.out.println("Even numbers are: " + EvenNums);
System.out.println("Odd numbers are: " + OddNums);
}
}

Related

Java, even number of even digits, odd number of odd digits

This program is essentially a game where the user must enter numbers to see which numbers are good: numbers with an even number of even digits, and an odd number of odd digits.
So first of all, the program ends when I enter a one digit number, which is not intentional. I assume that has something to do with the while being while (n > 0). There also is likely an issue with the if (numEven % 2 == 0......) because the print results seem almost random, with a number being good and the same number not being good sometimes.
Honestly, I am lost at this point. Thank you so much in advance for any help.
UPDATE: This code is working how I want it to, I just wanted to thank everybody who helped out! It's my first semester of computer science class, so I'm still rather new at this...excuse my mistakes that were likely pretty stupid :)
package quackygame;
import java.util.Scanner;
public class QuackyGame
{
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
int numEven = 0;
int numOdd = 0;
boolean isEven;
do
{
System.out.print("Enter a number > 0: ");
n = scan.nextInt();
while (n > 0)
{
if (n % 2 == 0)
{
//n is even
isEven = true;
numEven++;
}
else
{
//n is odd
isEven = false;
numOdd++;
}
n /= 10;
}
//if numEven is even and numOdd is odd
if (numEven % 2 == 0 && numOdd % 2 == 1)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n >= 0);
}
}
There are a few core issues in the code based on the desired results that you described. The most glaring issue I see is that you intend for the game to essentially "start from scratch" at the beginning of each round, but you never actually reset the numEven and numOdd variables. This is the source of your print results seeming random. For example, if you started a game and input the number:
34567
The game would process the number and say that it is a favorable number because it is odd, has an odd number of odd digits (3), and has an even number of even digits (2). However, upon playing the game again, it would execute the same code without setting the variables back to 0, which means that upon entering:
34567
The game would process this number as a bad number because the accumulated value of odd digits would be 6 instead of 3 (since 3 the first time + 3 the second time results in 6), and 6 is even. So what we want to do is this:
...
int n;
do
{
int numEven = 0;
int numOdd = 0;
System.out.print("Enter a number: ");
n = scan.nextInt();
...
By placing the numEven and numOdd declarations inside of the "do" block, they are local variables which only exist for the duration of the do block. We could also do something as simple as this:
...
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n > 0);
...
Just resetting the values will help us to keep track of the actual intended values of numOdd and numEven more consistently.
With regard to the program closing when you input a single digit number, I'm not sure. That doesn't make sense because since it is a do-while loop it should at least execute once, and issue one of the print statements. I'm loading this code into my IDE right now to give it a run through. I'll update my answer if I find something.
-EDIT-: Upon reading your question again, it seems that you may not be suggesting that the program closes before actually completing any of its functions, but simply that it closes at all. The reason for the closing of the program is that you are performing an integer division arithmetic function where you probably want to be using a different type of number. Let me explain:
In normal human counting, we have our natural set of numbers which have no decimal points. They usually start like this:
1, 2, 3, 4, 5 ...
Then we have a separate set of numbers for math where we operate with more precision:
0.5, 1.4232, 3.142 ...
When we are talking about numbers with normal human language, we assume that dividing 1 by 2 results in 0.5. However, computers do not implicitly know this. In order for a computer to reach the conclusion "0.5" from the division of 1 by 2, you need to explicitly tell it that it should use a certain type of number to produce that output.
The "normal" numbers I referenced earlier are most loosely related to the integer in programming. It's basically a number without a decimal point. What that means is that whenever you divide two integers together, you always get another integer as the result. So if you were to divide 1 by 2, the computer would not interpret the result as 0.5 because that number has a decimal. Instead, it would round it down to the nearest integer, which in this case is 0.
So for a more specific example referencing the actual question at hand, let's say we input the number 5 into our program. It goes through all of the calculations for odds and evens, but eventually gets to this line:
n /= 10
This is where things get funky. We are dividing two integers, but their result does not come out as a perfect integer. In this case, the result of 5 / 10 is again 0.5. But for the computer, since we are dividing two integers, the result 0.5 just won't do, so after rounding down to the nearest integer we get 0. At this point, there is one fatal mistake:
(while n > 0);
When we perform this check, we get false and the while loop ends. Why? Because after performing n /= 10, n becomes 0. And 0 is not greater than 0.
How can we fix this? The best thing to do is probably just use a floating point number to perform the calculations. In Java, this is pretty easy. All we really have to do is:
n /= 10.0
When Java sees that we are dividing by 10.0, which is not an integer, it automatically converts "n" to a floating point number to divide by 10.0. In this case then, if n is 5, our result in dividing 5 by 10.0 will be 0.5. Then, when we run:
(while n > 0);
This becomes true! And the loop does not break.
I am going to put all of these changes into my IDE just to confirm that everything is working as intended for me. I would suggest you give it a try too to see if it fixes your problems.
Hope this helps.
You are increasing numEven or numOdd count each time you input a number, and then you use if (numEven % 2 == 0 && numOdd % 2 == 1) , it is random because if you put number 33 for the first time => numOdd = 1; => true => "Wallace likes" , but next time you put 33 for the second time => numOdd = 2; => false => "Wallace doesnt like".
Edit* Maybe you wanted something like this?
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
boolean isEven;
do
{
System.out.print("Enter a number: ");
n = scan.nextInt();
//if 0, you leave the loop
if(n==0) {
System.out.println("You pressed 0, have a nice day");
break;
}
if (n % 2 == 0)
{
//it is even
isEven = true;
}
else
{
//it is not even
isEven = false;
}
//if even then he likes it, otherwise he does not
if (isEven)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
}
//put any contition here, lets say if you press 0 , you leave the loop
while (n != 0);
}

Sum of Absolutes

I was trying to solve the simple problem posted on HackerRank.
https://www.hackerrank.com/contests/w16/challenges/sum-of-absolutes
I solved the problem, however its getting time out error to those with input array of size 100000. Could someone help me optimize this code below so it does not timeout.
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print outputto STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int n= in.nextInt();
int q = in.nextInt();
in.nextLine();
int[] a = new int[n+1];
for(int i=1;i<=n;i++)
{
a[i]= in.nextInt();
}
for(int j=0;j<q;j++)
{
int l = in.nextInt();
int r = in.nextInt();
int sum=0;
for(int k=l;k<=r ;k++)
{
sum = Math.abs(sum+a[k]);
}
if(sum%2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
}
}
I think you need to completely rethink your solution: You don;t actually need to work out the summation in order to establish if the result is odd or even.
The observation that adding two even numbers or two odd number gives you an even; and that adding an even and an odd give you an odd for all numbers (positive and negative) should be all you need.
Think about whether there's a shortcut that will give you the same odd/even answer. For example, -8 and 8 are both even while -3 and 3 are both odd. Do you really need to take an absolute value to determine if the sum is even or odd?
---Edit: Another thought or two---
First thought.
Please take a look at Bitwise and Bit Shift Operations. There are bitwise ways to figure out if the number is negative (namely: The high-order bit is 1). And there are bitwise ways to tell if the number is odd (namely: The low-order bit of a positive number is 1 and the low order bit of a negative number is 0).
--- Edit: Second thought---
Could you compress the array by not storing the input numbers, but instead the parity of those numbers? For example, you could use boolean[] isOdd or BitSet isOdd? You could store -7 in position i as isOdd[i] = true; or isOdd.set(i);. (Since BitSet and boolean both initialize to all false, you would not change the boolean or BitSet in position j if position j were even; see BitSet.) Then your answer would consist of counting the odds (or flipping a boolean or not'ing a bit) in the requested set and answering odd if the sum were odd (or false or 0) or even if the sum were even (or true or 1).
Why should you use a BitSet or boolean array? You can pack more information into less memory, making it easier for Java to find the space and leading to fewer page faults should you go over a page boundary.
I'm going to give you two hints. First, always look for needlessly repeated operations (spoiler: how many times do you do Math.abs on each value in the set?). And second, file IO is very expensive. Look for a way to use Scanner more efficiently.

Detecting Common Elements in an Unsorted Array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I found a code which will detect common elements in an unsorted array. The program runs in linear time! But i did not understand the logic of the program. It would be very helpful if some one could explain the logic of the program.
Here is the code:
public class DeleteUnsortedDataFromArray {
public static List<Integer> findDuplicatesArray(int[] sequence){
int bitarray = 0;
for(int i=0; i< sequence.length; i++){
int x = 1;
x = x << sequence[i];
if((bitarray & x) != 0){
System.out.println("Duplicate found in given array: " + sequence[i]);
} else {
bitarray = bitarray | x;
}
}
return null;
}
public static void main(String[] args) {
int[] input = {1,1,2,3};
findDuplicatesArray(input);
}
}
What it does is to represent each found value as an 1 in a position of the bits composing an integer (bitarray).
The lines:
x = 1;
x = x << sequence[i];
Will put a 1 at the position given by the sequence value+1 (<< is a shift operator).
For example, if sequence[i] value is four, x will have the binary value: ...010000
The line:
(bitarray & x) != 0
Uses bit operation AND to check if a position has been already occupied and hence the valued found.
The problem is that this algorithm only works if your values at sequence are constrained to be low: Between 0 and 30 as there are 32 bits in an Java integer and the value 0 is represented as a 1 at the position 0 of bitarray.
You should consider too what happens when the sequence values are negative.
It works only as long as all values in the array belong to [0, number-of-bits-in-int). If of course you can say 'works' about a function that is supposed to return list of duplicates but always returns null.
You can understand the algorithm as using an array of booleans to test whether a value has occured previously in the array or not. Now instead of using an array of booleans, what you are doing is using the bits in an int to represent whether a value has occured previously or not. The code calls this "bitarray".
To set the Ith bit in an int, you use
x = (x | (1<< i));
Here '|' is the bitwise or operator.
And to test whether the Ith bit has been set you check the condition
if((x & (1<< i)) != 0){
}
here '&' is the bitwise and operator.
Moreover, the algorithm used above will only work if the range of values in the array is between 0 and 31 inclusive. That's because java ints are represented using 32 bits. However it consumes lesser space than other alternatives like using a HashSet or an explicit array of booleans.
However, if space is at a premium, and you know that the range of data in the array is small, you can consider using Bitset class (link).

Interesting thing happening when I take a number, multiply it by 10, and then add 1 [duplicate]

This question already has answers here:
Multiplication of two ints overflowing to result in a negative number
(5 answers)
Closed 9 years ago.
static int fn = 0;
static int sn = 0;
static boolean running = false;
public static void run()
{
while (running == true)
{
fn = numbers[0];
sn = numbers[1];
if (sign == 0)
{
input.setText(String.valueOf(fn));
}
}
}
static class one implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (Display.sign == 0)
{
Display.numbers[0] = Display.numbers[0] *10;
Display.numbers[0] = Display.numbers[0] +1;
}
}
}
This is the code for a calculator that I am programming (not all of it of course). This is the part where I display the number on the screen which I have done, but weirdly this works up until 10 characters
So after I get the program to display 1111111111 I want to do it once more and it gives me this weird number -1773790777. I am confused about how the program comes up with this. As you can see, above Display.numbers[] is the array I am storing the two numbers in. So to go over a place I multiply the number in the array by 10 then add 1. So how does this give me a negative number in the first place and what can I do to solve this problem?
Is your number overflowing?
You can check it by looking at Integer.MAX_VALUE (assuming you are using an integer). If you go over that you will loop will get weird results like this. See - http://javapapers.com/core-java/java-overflow-and-underflow/ for more details.
It's overflowing!
1111111111*10 + 1 = 11111111111 which is 0x2964619C7 in hexadecimal. It's a 34-bit value which can't be stored in a 32-bit int
In Java arithmetic operations wrap around by default, so if the result overflowed then it'll be wrapped back to the other end of the value range. See How does Java handle integer underflows and overflows and how would you check for it?
However due to the use of 2's complement, the result will be the lower bits of the result 11111111111 mod 232 = 2521176519 = 0x964619C7 which is -1'773'790'777 in 32-bit int, that's why you see the number. You should read more on binary, that's the basic of nowadays computers
In Java 8 you'll have an easier way to detect overflow with the new *Exact methods
The platform uses signed two's complement integer arithmetic with int and long primitive types. The developer should choose the primitive type to ensure that arithmetic operations consistently produce correct results, which in some cases means the operations will not overflow the range of values of the computation. The best practice is to choose the primitive type and algorithm to avoid overflow. In cases where the size is int or long and overflow errors need to be detected, the methods addExact, subtractExact, multiplyExact, and toIntExact throw an ArithmeticException when the results overflow. For other arithmetic operations such as divide, absolute value, increment, decrement, and negation overflow occurs only with a specific minimum or maximum value and should be checked against the minimum or maximum as appropriate.
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html

Java - 1 more step to complete program (homework) [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
My last step involves getting the integer percent of the sum.
So if I enter:
2
1
1
2
The output should be:
2, which is 33.333% of the sum.
1, which is 16.666% of the sum.
1, which is 16.666% of the sum.
2, which is 33.333% of the sum.
Since I am very new to arrays, I am extremely puzzled. I don't understand how to get the percent since user can enter any amount of integers. If it was only 2 integers, just say 2 and 2, they each would be 50 percent
import java.util.Scanner;
public class Integers {
/* program 7-1*/
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers will you enter?");
int size = keyboard.nextInt();
int[] entry = new int[size];
System.out.println("Enter " + entry.length + " integers, one per line:");
int sum = 0;
for (int index = 0; index < entry.length; index++)
{
entry[index] = keyboard.nextInt();
sum += size;
}
System.out.println("The sum is " + sum + "." + "\nThe numbers are:" );
}
}
Now that you have all entries and the sum, you are almost there:
You need another loop to go over entries one at a time
To calculate percentage, multiply the entry by 100.0, and then divide by the sum. Note the dot zero at the end of 100.0 - it's there on purpose
If you are on Java 5 or later, a very convenient way of printing out a number followed by percentage sign is printf. Note, however, that the percent sign % needs to be escaped.
What answer are you getting that's incorrect? That's what is puzzling. I looked at your code, but I don't see any division, percentage calculation, or output.
I compiled and ran your code. Here's the output I got. So far, so good. What's wrong? What's your question?
"C:\Program Files\Java\jdk1.7.0_02\bin\java" -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 120.11\bin" com.intellij.rt.execution.application.AppMain cruft.Integers
How many numbers will you enter?
4
Enter 4 integers, one per line:
2
1
1
2
The sum is 16.
The numbers are:
Process finished with exit code 0
Write more code. Be careful to remember that integer division isn't what you want; percentages need to be doubles.
int x = 1/2; // x will equal zero. know why?
You've already calculated the sum. You know that if you take in ten numbers, no matter how many or what their values are, the percentage of the sum that each one will represent is the number divided by the sum. Is that what you're asking?
1 hour later:
It's been a whole hour, and you seem to think that writing comments is more educational than actually writing the four lines of code that you need. Okay, I'll bite - here's your solution. I'll risk the wrath of all those who will be outraged by someone who does homework. I want you to see how ridiculous it is that you wouldn't even attempt four lines of code:
import java.util.Scanner;
public class Integers {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers will you enter?");
int size = keyboard.nextInt();
int[] entry = new int[size];
System.out.println("Enter " + entry.length + " integers, one per line:");
int sum = 0;
for (int index = 0; index < entry.length; index++) {
entry[index] = keyboard.nextInt();
sum += entry[index]; // this was wrong - I fixed it.
}
// This is all you had to do.
for (int anEntry : entry) {
System.out.println(String.format("value: %d %6.2f%%", anEntry, anEntry * 100.0 / sum));
}
System.out.println(String.format("total: %d %6.2f%%", sum, 100.0));
}
}
Since this is not homework, I am not going to give you an answer, but give you an approach that you can figure out to implement (and learn from :-D)
create two arrays of the length the user enters and one counter for the second. the first array will be the one you currently have. The second will store unique values and the counter will represent how many unique values are in that array. When the user enters a value, check to see if its in the current array, if not add it to unique and increment the counter. Then iterate through the unique array at the end of your program performing the calculation.
--cheers
If you have an unknown number of integers separated by a ' ' space, you could take them in as a String and use the String.split function - you can find documentation at http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split(java.lang.String) - which will give you an array which is as large as you need it to be, and whose length is stored in the length field of the array.

Categories

Resources