Explanation for `check /= 2;` - java

I need some explanation for this code.
This is the example code given by others.
for ( int i = 1; i <= 8; i++ )
{
if(check % 2 == 0)
sum += i;
else
sum -= i;
check /= 2; <--- Need explanation for this line.
}
But in the Pseudo code, there is no check /= 2; procedure.
Here is the full Pseudo code.
int binary = 0;
int sum;
while(binary<256)
sum = 0;
for(go through all 8 digits)
if the i-th digit is 0
sum += i
if the i-th digit is 1
sum -= i
end for
if sum == 0
output
binary++
end while
So, what is the purpose for that line of code?
Since sum, binary, and check is initialize as 0.
I have written this code using the Pseudocode given above.
But seems like my code will duplicate the output and one more problem, the format.
I want the output be like this format:
Enter a number : 3
-1 -2 +3 = 0
1 +2 -3 = 0
But my currently output is:
Enter a number : 3
-1 -2 3 = 0
1 2 -3 = 0
Here is my code:
CODE IS REMOVED!
Solved!
I'm too focus on the for-loop for the output part, hence miss the while-loop for the binary, because the pseudocode is for 256 possible solutions, hence, there will be same output for the front part, example:
1 - 2 - 3 + 4 = 0
1 - 2 - 3 + 4 + 5 - 6 - 7 + 8 = 0
Hence, the pseudocode may give an same output. So, since the solution is in 2 ^ n where n = 1, 2, 3, ... form, so change the
while( binary < 256 ) ---> while ( binary < Math.pow(2, input))
should solve it.
The format and the duplicate of the answer are solved.

This is the way to go through all digits. The most right digit is retrieved by check % 2, and after checking it, you shift check one digit (bit) to the right by check /= 2 (equals to check = check / 2;)

With this algorithm you are counting all the bit set to 1 and set to 0.
check /= 2;
it is like
check = check / 2;
and you can use it to shift all bits right by one.
For example:
(binary) 101 / (decimal) 2 = (binary) 10
that is 101 shift right by one digit.

Let's look at this line:
check /= 2;
In Java it is equivalent to the following simple statement:
check = check / 2;
Now let's find out the purpose behind it:
The right most digit is checked by check % 2
Then it is shifted right by one digit by check /= 2

check /= 2 is equivalent to check = check / 2;
its just a way of combining multiple assignments into a single one, like sum += 2 is equivalent to sum = sum + 2;

Related

Meaning of the formula how to find lost element in array?

The task is to find lost element in the array. I understand the logic of the solution but I don't understand how does this formula works?
Here is the solution
int[] array = new int[]{4,1,2,3,5,8,6};
int size = array.length;
int result = (size + 1) * (size + 2)/2;
for (int i : array){
result -= i;
}
But why we add 1 to total size and multiply it to total size + 2 /2 ?? In all resources, people just use that formula but nobody explains how that formula works
The sum of the digits 1 thru n is equal to ((n)(n+1))/2.
e.g. for 1,2,3,4,5 5*6/2 = 15.
But this is just a quick way to add up the numbers from 1 to n. Here is what is really going on.
The series computes the sum of 1 to n assuming they all were present. But by subtracting each number from that sum, the remainder is the missing number.
The formula for an arithmetic series of integers from k to n where adjacent elements differ by 1 is.
S[k,n] = (n-k+1)(n+k)/2
Example: k = 5, n = 10
S[k,n] = 5 6 7 8 9 10
S[k,n] = 10 9 8 7 6 5
S[k,n] = (10-5+1)*(10+5)/2
2S[k,n] = 6 * 15 / 2
S[k,n] = 90 / 2 = 45
For any single number missing from the sequence, by subtracting the others from the sum of 45, the remainder will be the missing number.
Let's say you currently have n elements in your array. You know that one element is missing, which means that the actual size of your array should be n + 1.
Now, you just need to calculate the sum 1 + 2 + ... + n + (n+1).
A handy formula for computing the sum of all integers from 1 up to k is given by k(k+1)/2.
By just replacing k with n+1, you get the formula (n+1)(n+2)/2.
It's simple mathematics.
Sum of first n natural numbers = n*(n+1)/2.
Number of elements in array = size of array.
So, in this case n = size + 1
So, after finding the sum, we are subtracting all the numbers from array individually and we are left with the missing number.
Broken sequence vs full sequence
But why we add 1 to total size and multiply it to total size + 2 /2 ?
The amount of numbers stored in your array is one less than the maximal number, as the sequence is missing one element.
Check your example:
4, 1, 2, 3, 5, 8, 6
The sequence is supposed to go from 1 to 8, but the amount of elements (size) is 7, not 8. Because the 7 is missing from the sequence.
Another example:
1, 2, 3, 5, 6, 7
This sequence is missing the 4. The full sequence would have a length of 7 but the above array would have a length of 6 only, one less.
You have to account for that and counter it.
Sum formula
Knowing that, the sum of all natural numbers from 1 up to n, so 1 + 2 + 3 + ... + n can also be directly computed by
n * (n + 1) / 2
See the very first paragraph in Wikipedia#Summation.
But n is supposed to be 8 (length of the full sequence) in your example, not 7 (broken sequence). So you have to add 1 to all the n in the formula, receiving
(n + 1) * (n + 2) / 2
I guess this would be similar to Missing Number of LeetCode (268):
Java
class Solution {
public static int missingNumber(int[] nums) {
int missing = nums.length;
for (int index = 0; index < nums.length; index++)
missing += index - nums[index];
return missing;
}
}
C++ using Bit Manipulation
class Solution {
public:
int missingNumber(vector<int> &nums) {
int missing = nums.size();
int index = 0;
for (int num : nums) {
missing = missing ^ num ^ index;
index++;
}
return missing;
}
};
Python I
class Solution:
def missingNumber(self, nums):
return (len(nums) * (-~len(nums))) // 2 - sum(nums)
Python II
class Solution:
def missingNumber(self, nums):
return (len(nums) * ((-~len(nums))) >> 1) - sum(nums)
Reference to how it works:
The methods have been explained in the following links:
Missing Number Discussion
Missing Number Solution

CodeAbbey Challenge 14 data entry issues?

int fnum = Integer.parseInt(split[0]);// holds 5
//split[] holds each line of the file.
double sum = fnum;// sum = 5
double i = 0.0;
double last = 0.0;
for(int j = 1; j<(split.length-1);j++)
{
i = Integer.parseInt(split[j].replaceAll("[^0-9]", ""));
if(split[j].charAt(0) == '*')
{
sum = sum * i;
}
else if(split[j].charAt(0) == '/')
{
sum = sum / i;
}
else if(split[j].charAt(0) == '+')
{
sum = sum + i;
}
else if(split[j].charAt(0) == '-')
{
sum = sum - i;
}
else if(split[j].charAt(0) == '%')
{
sum = sum % i;
}
}
System.out.println(sum);// Prints 1.0
}
}
/*
Actual Data File Imported
5
+ 3
* 7
+ 10
* 2
* 3
+ 1
% 11
Answer should be : 1
*/
Alright My code may look messy, but I tried hard on it. Gave up a few times but tried again. My question is for smaller data sets such as the one I imported and commented out on the code on the last few lines, work fine. But for bigger data sets it's all wrong why is that? I've tried making al my data sets double to get bigger values but somehow it's wrong?
I'm a beginner so far, any help would be greatly appreciated.
To be more specific on the problem I imported the file, I made it all a String, line by line, then I added it all in a String array so each line was in a string array for example split[1] would print + 3. Now after that I isolated the number and the symbol in the if loop wrapped in a forloop to go over all the sets. Now the if loop captures the symbols and then does the appropriate arithmetic. SomeHow it didn't though? And I used a double instead of an int for sum. That didn't help.I believe the if statement could be the issue.
Not sure if you still need the answer but, here's a tip:
The whole point of that specific exercise was to learn the modular arithmetic, which is that if you sum up/multiply the remainders of all of the numbers, you get the same answer as you would using the numbers given, that is if you apply the same number that's after % for all of them.
For example:
14
+ 78
* 9
* 3
+ 4
% 3
After all of the applied operations, the numbers above % 3 result in 2488.
And so 2488 % 3 = 1.
So if you apply % 3 to each one of the numbers, including the initial one, you get the same answer, using the same operations on their remainders of course and dividing the sum again by 3.
14 % 3 = 2
78 % 3 = 0
9 % 3 = 0
3 % 3 = 0
4 % 3 = 1
So, you get 2 + 0 * 0 * 0 + 1 which equals to 1.
And 1 % 3 = 1 which is the same as 2488 % 3 = 1.
My point being, you should apply modulo to every one of the numbers, so you get little numbers and don't even have the big ones you're having problems with.
Hope this was clear enough and hope it helps.

How to find shortest path in both directions of a number with over wrapping?

Let's say I have to pick a number from 0-10.
The number I pick is 6.
The next number I want to pick is 0.
Now the rules are I have to keep incrementing the number by 1 or decrementing it by 1, the number can also wrap around the last number.
Now whats most important is to find which direction is shortest to take.
So
6-5-4-3-2-1-0 = 7 moves.
6-7-8-9-10-0 = 6 moves.
So incrementing wins in this case.
Well I came up with this code (probably broken)
int movesInc = 1;
int movesDec = 1;
int curNumber = 6;
int nextNumber = 0;
while((curNumber-- % 11) != nextNumber)
movesDec++;
while((curNumber++ % 11) != nextNumber)
movesInc++;
Now instead of using a while loop in both directions.. and finding out which takes less moves..
any way to do this without a while loop? just maybe some kind of mathematical equation?
Your code doesn't in fact work properly for two reasons:
You should be working modulo 11 instead of 10 (I see you've now fixed this per my earlier comment).
The % operator in Java and C++ doesn't deal with signs the way you think.
This does work, though it's not pretty, and it doesn't need loops.
It is tested for the start at 6 and end at 0, and I expect it works generally. For a different range, you'd of course need to change the number added when the result goes negative.
int curNumber = 6;
int nextNumber = 0;
int movesInc = (nextNumber - curNumber) + 1
+ ((nextNumber > curNumber)? 0: 11);
int movesDec = (curNumber - nextNumber) + 1
+ ((nextNumber < curNumber)? 0: 11);
The + 1 here is because you're counting both endpoints. The ternary expression is what handles going around 0.
int curNumber;
int nextNumber;
//calculate the modulo size by the highest number
int module = 10 + 1;
//calculate the direct distance to the nextNumber
int directDist = nextNumber - curNumber;
int nextNumberWrapped;
//calculate the wrapped distance, deciding the direction which wraps
if(directDist < 0)
//wrapping in positive direction: 10 -> 0
nextNumberWrapped = nextNumber + module;
else
//wrapping in negative direction 0 -> 10
nextNumberWrapped = nextNumber - module;
//calculating the wrapped distance
int wrappedDist = nextNumberWrapped - curNumber;
//assume the directDist to be shortest
int shortestDist = directDist;
//proof wrong if neccessary (compare the distances absolute values)
if(abs(wrappedDist) < abs(directDist))
//save the signed distance
shortestDist = wrappedDist;
The absolute value of shortestDist tells you the length of the shortest distance and the sign gives you the direction.
So when the sign is negative you have to decrement and when it is positive you must increment to go the shortest way.
http://ideone.com/0yCDw
Also your example seems wrong. Each - between the numbers is one step, leaving you with one step less than you counted:
6-5-4-3-2-1-0
^ ^ ^ ^ ^ ^
1 2 3 4 5 6 -> 6 moves
6-7-8-9-10-0
^ ^ ^ ^ ^
1 2 3 4 5 -> 5 moves

How can i get the next highest multiple of 5 or 10

From a given double I want to get the next highest number according to some rules which, since I have some difficulty describing them, I will illustrate by examples:
Input Desired output
------- --------------
0.08 0.1
0.2 0.5
5 10
7 10
99 100
100 500
2345 5000
The output should be in some sense the 'next highest multiple of 5 or 10'.
I hope this is understandable; if not, let me know.
The implementation will be in java and input will be positive doubles.
function top5_10 (x) {
var ten = Math.pow(10, Math.ceiling(Math.ln(x)/Math.LN10)));
if (ten > 10 * x) { ten = ten / 10; }
else if (ten <= x) { ten = 10 * ten; }
return x < ten / 2 ? ten / 2 : ten;
}
or something like this :-)
Here's a function that works on the sample data:
def f(x):
lx = log10(x)
e = floor(lx)
if (lx - e) < log10(5):
return 5 * 10 ** e
else:
return 10 ** (e+1)
Pseudo code should be something like this:
If number > 1
n = 1
While(true)
If(number < n)
return n
If(number < n*5)
return n*5
n = n*10
Else
n = 1.0
While(true)
If(number > n/2)
return n
If(number > n/10)
return n*2
n = n/10.0
For numbers > 1, it checks like this:
if < 5, 5. if <10, 10, if < 50, 50.
For numbers < 1, it checks like this:
if > 0.5 1. if > 0.1, 0.5. etc.
If you intend to use doubles and need precise result, all methods using double-precision multiply/divide/log10 are not working (or at least are hard to implement and prove correctness). Multi-precision arithmetic might help here. Or use search like this:
powers = [1.e-309, 1.e-308, ..., 1.e309]
p = search_first_greater(powers, number)
if (number < p / 2.) return p / 2.
return p
search_first_greater may be implemented as:
linear search,
or binary search,
or direct calculation of the array index by n=round(log10(number)) and checking only powers[n-1 .. n]
or using logarithm approximation like cutting the exponent part out of the number and checking 4 elements of powers[].

Sum of numbers under 10,000 that are multiples of 3, 5 or 7 in Java

I know how to get the program to add up the sums of the multiple for each of 3, 5 and 7, but I'm not sure how I'd get the program to only use each number once. For example, I can get the program to find out all of the numbers and add them up for 3 and then do the same for 5, but then the number 15 would be in the final number twice. I'm not sure exactly how I'd get it to only take the number once. Thanks for any help.
While the generate-and-test approach is simple to understand, it is also not very efficient if you want to run this on larger numbers. Instead, we can use the inclusion-exclusion principle.
The idea is to first sum up too many numbers by looking at the multiples of 3, 5 and 7 separately. Then we subtract the ones we counted twice, i.e. multiples of 3*5, 3*7 and 5*7. But now we subtracted too much and need to add back the multiples of 3*5*7 again.
We start by finding the sum of all integers 1..n which are multiples of k. First, we find out how many there are, m = n / k, rounded down thanks to integer division. Now we just need to sum up the sequence k + 2*k + 3*k + ... + m*k. We factor out the k and get k * (1 + 2 + ... + m).
This is a well-known arithmetic series, which we know sums to k * m * (m + 1)/2 (See triangle number).
private long n = 9999;
private long multiples(long k) {
long m = n / k;
return k * m * (m + 1) / 2:
}
Now we just use inclusion-exclusion to get the final sum:
long sum = multiples(3) + multiples(5) + multiples(7)
- multiples(3*5) - multiples(3*7) - multiples(5*7)
+ multiples(3*5*7);
This will scale much better to larger n than just looping over all the values, but beware of overflow and change to BigIntegers if necessary.
The easiest approach would be to use a for loop thus:
int sum = 0;
for(int i=1; i<10000; i++)
{
if (i % 3 == 0 || i % 5 == 0 || i % 7 == 0)
sum += i;
}
Use a Set to store the unique multiples, and then sum the values of the Set.
I would use a Set. This way you are guaranteed that you won't get any duplicates if they are your main problem.
One simple solution would be to add each number thats a multiple of 3,5, or 7 to an Answer list. And then as you work thru each number, make sure that its not already in the answer list.
(pseudo-code)
List<int> AnswerList;
List<int> MultiplesOfFive;
List<int> MultiplesOfSeven;
List<int> MultiplesOfThree;
for (int i = 0 ; i < 10000; i++)
{
if ( i % 3 == 0 && AnswserList.Contains(i) == false)
{
MultiplesOfThree.Add(i);
AnswerList.Add(i);
}
if ( i % 5 == 0 && AnswserList.Contains(i) == false)
{
MultiplesOfFive.Add(i);
AnswerList.Add(i);
}
if ( i % 7 == 0 && AnswserList.Contains(i) == false)
{
MultiplesOfSeven.Add(i);
AnswerList.Add(i);
}
}
for the solution that loops 1 to 1000 use i<=10000 otherwise it'll skip 10000 itself which is a multiple of 5. Apologies, for some reason i can't post this as a comment

Categories