Precedence in expression including parentheses and int cast in java [duplicate] - java

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 3 years ago.
I have the following expression in my code
int n = ((int) Math.sqrt(4 * 4 + 5) - 1) / 2;
Can someone tell me the precedence in which the expression is evaluated?
Logically I would evaluate the expression in the following way:
4 * 4 + 5 = 16 + 5 = 21
Math.sqrt(21) ~ 4.58
4.58 - 1 = 3.58
(int) 3.58 = 3
3 / 2 = 1.5
However the code evaluates to 1.

You almost got it. The only difference (which doesn't matter for the result) is that the cast is evaluated
before the subtraction, and you're using integer division:
4 * 4 + 5 = 16 + 5 = 21
Math.sqrt(21) ~ 4.58
(int) 4.58 = 4 (cast first)
4 - 1 = 3
3 / 2 = 1 (integer division)

The order you suggest is correct.
The keypoint is the last operation: the result of an int divided by an int is an int as well.
To fix this, one of the two number should be a float (or a double):
float n = ((float)(int) (Math.sqrt(4 * 4 + 5) - 1)) / 2;
In this way you divide a float by an int, and the result will be a float.
Or better:
double n = (Math.sqrt(4 * 4 + 5) - 1) / 2;
Because the cast to int of Math.sqrt() isn't useful.
Please note that the first operation does exactly what you ask with the round of the Math.sqrt(), while the second one doesn't.

Related

How to calculate Base64 encoded string length?

I've read following topic and found this formula there:
length = 4*(n/3)
I started to test it:
1 symbol:
Base64.getEncoder().encodeToString("1".getBytes()) =>MQ==(4 symbols)
2 symbols:
Base64.getEncoder().encodeToString("12".getBytes()) =>MTI= (4 symbols)
5 symbols:
Base64.getEncoder().encodeToString("12345".getBytes()) =>MTIzNDU=(8 symbols)
8 symbols:
Base64.getEncoder().encodeToString("12345678".getBytes()) =>MTIzNDU2Nzg=(12 symbols)
21symbols:
Base64.getEncoder().encodeToString("123456789012345678901".getBytes()) => MTIzNDU2Nzg5MDEyMzQ1Njc4OTAx (28 symbols)
Looks like this formula doesn't work.
Can you please explain mu results?
With 64 digits (26) one digit can represent 6 bits.
Hence 4 digits can represent exactly 4*6 bits = 3 bytes.
(Using ÷ for explicit integer division:)
With n bytes, 4*(n÷3) digits are needed plus for the remainder n%3 (0 < 3 bytes) there is a need for 0 upto 4 digits:
0 bytes (0 bits) 0 digits
1 byte (8 bits) 2 digits (12 bits) + "=="
2 bytes (16 bits) 3 digits (18 bits) + "="
Often there is a padding upto 4 digits/padding chars, using =.
This cannot be 0 as one then would add a byte 0x0.
Then the formula is 4 * Math.ceil(n / 3.0).
Without padding: Math.ceil(n * 8 / 6.0) = Math.ceil(n * 4 / 3.0) = (n * 4 + (3 - 1)) ÷ 3.
In java one should use int division only:
int base64Length(byte[] b) {
int n = b.length;
return (n * 4 + 2)/3;
}
Try length = 4*((n/3) + 1), where "/" is integer division.
Edit: Lexicore is correct, my formula fails when the remainder is zero.
int length = 4 * (n / 3);
if (n % 3 > 0) length++;

Addition in field with finite int elements?

I need to write a function (in Java) which has the following input:
int amountFieldElements
int summandOne
int summandTwo
amountFieldElement describes the amount of int numbers in a range starting from 1 (e.g. 1, 2, 3, 4 or just 1). summandOne is a int from this range, summandTwo can be any non-negative int.
The function has to add summandTwo to summandOne. If the result is bigger then amountFieldElement, it has to start over from 1.
I tried to simply use modulo: (summandOne + summandTwo) % amountFieldElements
But this is often wrong, e.g. (3 + 1) % 4 = 0 but I'd need it to be 4.
Example: If amountFieldElements = 4:
2 + 2 = 4 would stay as 4
3 + 2 = 5 would become 1
4 + 2 = 6 would become 2 etc
or for amountFieldElements = 1
1 + 0 = 1 would stay as 1
1 + 1 = 2 would also be 1
-> any result would be 1 here
something like this will work:
int result = (summandOne + summandTwo) % amountFieldElements;
if (result == 0) result = amountFieldElements;
another method, shorter but harder to understand is:
int result = (summandOne + summandTwo - 1) % amountFieldElements + 1;

Why does 012 % 10 = 0 in Java? [duplicate]

This question already has answers here:
Int with leading zeroes - unexpected result
(4 answers)
Closed 7 years ago.
I am trying following program.
int var = 012;
int result = var % 10;
output:
result = 0
I am not able to understand why java is not able to consider 012 as 12.
In Java, integer literals that start with 0 are interpreted as octal numbers.
So, 012 is the number 1 x 8 + 2 = 10 (in decimal), not 12 (decimal).
012 % 10 == 10 % 10 == 0

I dont understand how the different amounts are calculated [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I don't understand how the results are calculated
int halfDollar = remainingAmount / 50;
remainingAmount = remainingAmount % 50;
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
ETC.....
import java.util.Scanner;
public class Program3
{
public static void main(String [] args)
{
Scanner kbd = new Scanner(System.in);
System.out.print("Please enter the total dollar amount in the piggy bank: $");
double amount = kbd.nextDouble();
int remainingAmount = (int)(amount * 100);
int halfDollar = remainingAmount / 50;
remainingAmount = remainingAmount % 50;
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
int numberOfNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
int numberOfPennies = remainingAmount;
System.out.println(String.format("In $" + "%.2f", amount) + " worth of pennies there are:");
System.out.println(halfDollar + " half dollar(s), " + numberOfQuarters + " quarter(s), " + numberOfDimes + " dime(s), " + numberOfNickels + " nickle(s), and " + numberOfPennies + " cent(s).");
}
}
It's simple, you multiple the number of dollars by 100 and you get the number of cents, then you calculate how many nickels, dimes etc that would be.
For example, $5.26 is 526 cents, which is 10 half dollars ($5), 1 quarter, 1 penny.
Integer division gives you the number of times X is contained in Y, and modulus (%) gives you the remainder.
526 / 50 = 10
526 % 50 = 26
26 / 25 = 1
26 % 25 = 1
1 / 10 = 0
1 % 10 = 1
1 / 5 = 0
1 % 5 = 1
1 / 1 = 1
1 % 1 = 0
Obviously, what that does is break the amount of money in the least number of coins by giving you as many coins of the highest denomination first, then the highest number of coins of the next denomination etc.
For avoiding fractions you multiply value with 100. Making calculations with fractions is a little bit difficult.
For example instead of making calculations with $1.25 programmers prefer to make calculations 125. It makes to easy understanding.
If you divide(/) X to Y you find the number of Y that X contains.
If you take mod(%) X of Y you find the remainder of X divided by Y
Think that $1.43 entered.
1.43 * 100 = 143
143 / 50 = 2 -> Half dollar
143 % 50 = 43 -> remainder of division
43 / 25 = 1 -> Quarter
43 % 25 = 18 -> remainder of division
18 / 10 = 1 -> Dimes
18 % 10 = 8 -> remainder of division
8 / 5 = 1 -> Nickels
8 % 5 = 3 -> remainder of division
There is no more division last remainder is pennies and it is 3
The / operator when applied to ints provides integer division. That is: division where the fractional part is thrown away.
For example: 10 / 3 gives 3.
Since:
10 divided by 3 is 3.3333333 recurring.
Throwing away the fractional part (0.3333333 recurring) gives the result 3.
The % operator provides modulus or the remainder of integer division. That is: the numerator minus the greatest multiple of the denominator that is less than the numerator.
For example: 10 % 3 gives 1.
Since:
the numerator is 10
the denominator is 3
The result of the integer division 10 / 3 is 3 (as we worked out above)
The greatest multiple of the denominator (3) that is less than the numerator (10) is 3, since 3 * 3 is 9 and no multiple of 3 is greater than 9 but less than 10.
Subtracting that (9) from the numerator (10) you get 10 - 9 which is the result 1.
An easier way to understand this is that integer / is division of whole things that can't be split. So you might want to divide 10 marbles (which you don't want to split into pieces) evenly between 3 people. Then each person gets 3 marbles, but there is 1 marble left over.
Note: that the greatest multiple of the denominator is exactly the result of the integer division (3 in this case, as in 10 / 3 is 3)
Note: You could also work this out by multiplying the fractional part by the result of the integer division (which we worked out was 10 / 3 =3). Giving 0.33333... * 3 which is the result 1.

Division by subtration - dividing the remainder by subtration?

We can divide a number by subtraction and stop at the remainder as shown here.
But how do we continue to divide the remainder by subtraction ? I looked on google and could not find such answers. They don't go beyond the remainder.
For example, lets say we have
7/3.
7-3 = 4
4-3 = 1
So, we have 2 & (1/3). How do we do the 1/3
division using only subtraction or addition ?
REPEAT -
Please note that I dont want to use multiplication or division operators to do this.
You can get additional "digits", up to any arbitrary precision (in any base you desire, I'll use base 10 for simplicity but if you're trying to implement an algorithm you'll probably choose base 2)
1) Perform division as you've illustrated, giving you a quotient (Q=2), a divisor (D=3), and a remainder (R=1)
2) If R=0, you're done
3) Multiply R by your base (10, R now =10)
4) Perform division by subtraction again to find R/D (10/3 = 3+1/3).
5) Divide the resulting quotient by your base (3/10 = 0.3) and add this to what you got from step 1 (now your result is 2.3)
6) Repeat from step 2, dividing the new remainder (1) by 10 again
While it sounds an awful lot like I just said division quite a few times, we're dividing by your base. I used 10 for simplicity, but you'd really use base 2, so step 3 is really a left shift (by 1 bit every time) and step 5 is really a right shift (by 1 bit the first time through, 2 bits the second, and so on).
7/3.
7-3 = 4
4-3 = 1
7/3 = 2 R 1
1*10 = 10
10-3 = 7
7-3 = 4
4-3 = 1
10/3 = 3 R 1
7/3 = 2 + 3/10 R 1
7/3 = 2.3 R 1
1*10 = 10
10-3 = 7
7-3 = 4
4-3 = 1
10/3 = 3 R 1
7/3 = 2.3 + 3/100 R 1
7/3 = 2.33 R 1
And so on until you reach any arbitrary precision.
If you want to keep going to get decimal digits, multiply the remainder by a power of 10.
E.g. if you want 2.333, then you can multiply remainder by 1000, and then repeat the algorithm.
It depends on what you are asking.
If you are asking how to get the end fraction and simply it, let's take a different example.
26 / 6.
26 - 6 = 20 count 1
20 - 6 = 14 count 2
14 - 6 = 8 count 3
8 - 6 = 2 count 4
(In code, this would be accomplished with a for loop)
Afterwards, we would have 4 2/6. To simplify, switch the dividend and divisor:
6 / 2.
6 - 2 = 4 count 1
4 - 2 = 2 count 2
2 - 2 = 0 count 3
If this finishes without a remainder, show as 1 over the count.
In pseudo-code:
int a = 26;
int b = 6;
int tempb = 6;
int left = 26;
int count = 0;
int count2 = 0;
left = a - b;
for(count; left > b; count++){
left -= b;
}
if(left > 0){
for(count2; tempb > left; count2++){
tempb -= left;
}
console.log("The answer is " + count + " and 1/" + count2);
I hope this answers your question!
Here is a complete program that uses only + and -, translate to your language of choice:
module Q where
infixl 14 `÷` `×`
a × 0 = 0
a × 1 = a
a × n = a + a×(n-1)
data Fraction = F Int [Int]
a ÷ 0 = error "division by zero"
a ÷ 1 = F a []
0 ÷ n = F 0 []
a ÷ n
| a >= n = case (a-n) ÷ n of
F r xs -> F (r+1) xs
| otherwise = F 0 (decimals a n)
where
decimals a n = case (a × 10) ÷ n of
F d rest = (d:rest)
instance Show Fraction where
show (F n []) = show n
show (F n xs) = show n ++ "." ++ concatMap show (take 10 xs)
main _ = println (100 ÷ 3)
It is easy to extend this in such a way that the periodic part of the fraction is detected, if any. For this, the decimals should be tuples, where not only the fractional digit itself but also the dividend that gave rise to it is kept.
The printing function could then be adjusted to print infinite fractions like 5.1(43), where 43 would be the periodic part.

Categories