I have the following variable decelrations, assignments and variable declerations
variable e is an expression statement which should return the value of the evaulated variables in the expression;
What is the order of precdence of the opperators in the e variable?
Computed it equals = 60;
With a calculator I get 422;
int a, b, c, d;
a = 10;
b = 2;
c = 1;
d = 20;
e = a + b * d / c + a + b / d;
e = 10 + 2 * 20 / 1 + 10 + 2 / 20;
e = 60;
Actually the answer is 60.1 but since variables are int its showing 60. It is happening as below
10 + (2 * (20 / 1)) + 10 + (int)(2 / 20) = 10 + (2 * 20) + 10 + (int)0.1
= 10 + 40 + 10 + 0 = 60
Here is a link outlining operator precedence. As for your result, this can also be attributed to integer division (which takes the floor of the result; for instance, 2/20 = 0).
Just like in school, multiplication and division have priority over addition. So you have:
10 + 2 * 20 / 1 + 10 + 2 / 20 = 10 + 40 + 10 + 0 = 60
* takes first precedence so first, 2*20 =40, 10 + 40 / 1 + 10 + 2 / 20;
/ takes precedence so , 10 + 40 + 10 + 0;
+ takes precedence so, 60
Here is link for operator precedence: Operator precedence
Related
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.
I am currently looking to find the largest amount of consecutive odd integers added together to equal a target number.
My current code to find 3 consecutive integers looks like
public class consecutiveOdd {
public static void main(String[] args){
int target = 160701;
boolean found = false;
for(int i = 1; i < target; i++){
if(i + (i+2) + (i+4) == target){
System.out.print(i + " + " + (i+2) + " + " + (i+4));
found = true;
}
}
if(!found){
System.out.println("Sorry none");
}
}
}
I am thinking there will need to be a while loop building iterations of (i+2) increments but am having trouble with developing a correct algorithm. Any help or tips will be much appreciated!
Best,
Otterman
Let's say that the answer is equal to k (k > 0). Then for some odd i we can write: i + (i + 2) + (i + 4) + ... + (i + 2k - 2) = target. You can see that this is a sum of arithmetic progression, therefore you can use a well known formula to compute it. Applying the formula we can get:
i = target/k - k + 1.
Basing on this formula I would suggest the following algorithm:
Iterate over the value of k.
If target/k - k + 1 is a positive odd integer, update the answer.
Simple implementation.
int answer = -1;
for (int k = 1;; k++) {
int i = target / k - k + 1;
if (i <= 0) {
break;
}
// Check if calculated i, can be the start of 'odd' sequence.
if (target % k == 0 && i % 2 == 1) {
answer = k;
}
}
The running time of this algorithm is O(sqrt(target)).
Looking at the pattern:
For 1 summand, i = target
For 2 summands, the equation is 2*i + 2 = target, so i = (target - 2) / 2
For 3 summands, the equation is 3*i + 6 = target, so i = (target - 6) / 3
For 4 summands, the equation is 4*i + 12 = target, so i = (target - 12) / 4
etc. Clearly i must be an odd integer in all cases.
You could work out the general expression for n summands, and simplify it to show you an algorithm, but you might be able to see an algorithm already...
Applying #rossum's suggestion:
For 1 summand, 2m + 1 = target
For 2 summands, 2m + 1 = (target - 2) / 2, so m = (target - 4) / 4
For 3 summands, 2m + 1 = (target - 6) / 3, so m = (target - 9) / 6
For 4 summands, 2m + 1 = (target - 12) / 4, so m = (target - 16) / 8
The sum of a sequence of n odd integers, can be calculated as the average value (midpoint m) multiplied by the number of values (n), so:
sum = 5 + 7 + 9 = m * n = 7 * 3 = 21
sum = 5 + 7 + 9 + 11 = m * n = 8 * 4 = 32
If n is odd then m will be odd, and if n is even then m will be even.
The first and last numbers of the sequence can be calculated as:
first = m - n + 1 = 8 - 4 + 1 = 5
last = m + n - 1 = 8 + 4 - 1 = 11
Other interesting formulas:
m = sum / n
m = (first + last) / 2
last = first + (n - 1) * 2 = first + 2 * n - 2
m = (first + first + 2 * n - 2) / 2 = first + n - 1
The longest sequence would have to start with the lowest possible first value, meaning 1, so we get:
sum = m * n = (first + n - 1) * n = n * n
Which means that the longest sequence of any given sum can at most be sqrt(sum) long.
So starting at sqrt(sum), and searching down until we find a valid n:
/**
* Returns length of sequence, or 0 if no sequence can be found
*/
private static int findLongestConsecutiveOddIntegers(int sum) {
for (int n = (int)Math.sqrt(sum); n > 1; n--) {
if (sum % n == 0) { // m must be an integer
int m = sum / n;
if ((n & 1) == (m & 1)) // If n is odd, mid must be odd. If n is even, m must be even.
return n;
}
}
return 0;
}
Result:
n = findLongestConsecutiveOddIntegers(160701) = 391
m = sum / n = 160701 / 391 = 411
first = m - n + 1 = 411 - 391 + 1 = 21
last = m + n - 1 = 411 + 391 - 1 = 801
Since sqrt(160701) = 400.875..., the result was found in 10 iterations (400 to 391, inclusive).
Conclusion:
Largest Amount of Consecutive Odd Integers to Equal 160701: 391
21 + 23 + 25 + ... + 799 + 801 = 160701
I've tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I'm not quite sure how to best implement it. I have my code and problem below.
The first 12 digits of pi are 314159265358.
We can make these digits into an expression evaluating to 27182 (first 5 digits of e)
as follows:
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182
or
3 + 1 - 415 * 92 + 65358 = 27182
Notice that the order of the input digits is not changed. Operators (+,-,/, or *) are simply inserted to create the expression.
Write a function to take a list of numbers and a target, and return all the ways that those numbers can be formed into expressions evaluating to the target
For example:
f("314159265358", 27182) should print:
3 + 1 - 415 * 92 + 65358 = 27182
3 * 1 + 4 * 159 + 26535 + 8 = 27182
3 / 1 + 4 * 159 + 26535 + 8 = 27182
3 * 14 * 15 + 9 + 26535 + 8 = 27182
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182
This problem is difficult since you can have any combination of numbers and you don't consider one number at a time. I wasn't sure how to do the combinations and recursion for that step. Notice that parentheses are not provided in the solution, however order of operations is preserved.
My goal is to start off with say
{"3"}
then
{"31", "3+1", "3-1", "3*1" "3/1"}
then
{"314", "31+4", "3+1+4", "3-1-4", "31/4", "31*4", "31-4"} etc.
then look at the every value in the list each time and see if it is target value. If it is, add that string to result list.
Here is my code
public static List<String> combinations(String nums, int target)
{
List<String> tempResultList = new ArrayList<String>();
List<String> realResultList = new ArrayList<String>();
String originalNum = Character.toString(nums.charAt(0));
for (int i = 0; i < nums.length(); i++)
{
if (i > 0)
{
originalNum += nums.charAt(i); //start off with a new number to decompose
}
tempResultList.add(originalNum);
char[] originalNumCharArray = originalNum.toCharArray();
for (int j = 0; j < originalNumCharArray.length; j++)
{
//go through every character to find the combinations?
// maybe recursion here instead of iterative would be easier...
}
for (String s : tempResultList)
{
//try to evaluate
int temp = 0;
if (s.contains("*") || s.contains("/") || s.contains("+") || s.contains("-"))
{
//evaluate expression
} else {
//just a number
}
if (temp == target)
{
realResultList.add(s);
}
}
tempResultList.clear();
}
return realResultList;
}
Could someone help with this problem? Looking for an answer with coding in it, since I need help with the generation of possibilities
I don't think it's necessary to build a tree, you should be able to calculate as you go -- you just need to delay additions and subtractions slightly in order to be able take the precedence into account correctly:
static void check(double sum, double previous, String digits, double target, String expr) {
if (digits.length() == 0) {
if (sum + previous == target) {
System.out.println(expr + " = " + target);
}
} else {
for (int i = 1; i <= digits.length(); i++) {
double current = Double.parseDouble(digits.substring(0, i));
String remaining = digits.substring(i);
check(sum + previous, current, remaining, target, expr + " + " + current);
check(sum, previous * current, remaining, target, expr + " * " + current);
check(sum, previous / current, remaining, target, expr + " / " + current);
check(sum + previous, -current, remaining, target, expr + " - " + current);
}
}
}
static void f(String digits, double target) {
for (int i = 1; i <= digits.length(); i++) {
String current = digits.substring(0, i);
check(0, Double.parseDouble(current), digits.substring(i), target, current);
}
}
First, you need a method where you can input the expression
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8
and get the answer:
27182
Next, you need to create a tree structure. Your first and second levels are complete.
3
31, 3 + 1, 3 - 1, 3 * 1, 3 / 1
Your third level lacks a few expressions.
31 -> 314, 31 + 4, 31 - 4, 31 * 4, 31 / 4
3 + 1 -> 3 + 14, 3 + 1 + 4, 3 + 1 - 4, 3 + 1 * 4, 3 + 1 / 4
3 - 1 -> 3 - 14, 3 - 1 + 4, 3 - 1 - 4, 3 - 1 * 4, 3 - 1 / 4
3 * 1 -> 3 * 14, 3 * 1 + 4, 3 * 1 - 4, 3 * 1 * 4, 3 * 1 / 4
3 / 1 -> 3 / 14, 3 / 1 + 4, 3 / 1 - 4, 3 / 1 * 4, 3 / 1 / 4
You can stop adding leaves to a branch of the tree when a division yields a non integer.
As you can see, the number of leaves at each level of your tree is going to increase at a rapid rate.
For each leaf, you have to append the next value, the next value added, subtracted, multiplied, and divided. As a final example, here are 5 of the fourth level leaves:
3 * 1 + 4 -> 3 * 1 + 41, 3 * 1 + 4 + 1, 3 * 1 + 4 - 1, 3 * 1 + 4 * 1,
3 * 1 + 4 / 1
Your code has to generate 5 expression leaves for each leaf until you've used all of the input digits.
When you've used all of the input digits, check each leaf equation to see if it equals the value.
My Javascript implementation:
Will improve the code using web worker later on
// was not allowed to use eval , so this is my replacement for the eval function.
function evaluate(expr) {
return new Function('return '+expr)();
}
function calc(expr,input,target) {
if (input.length==1) {
// I'm not allowed to use eval, so I will use my function evaluate
//if (eval(expr+input)==target) console.log(expr+input+"="+target);
if (evaluate(expr+input)==target) document.body.innerHTML+=expr+input+"="+target+"<br>";
}
else {
for(var i=1;i<=input.length;i++) {
var left=input.substring(0,i);
var right=input.substring(i);
['+','-','*','/'].forEach(function(oper) {
calc(expr+left+oper,right,target);
},this);
}
}
};
function f(input,total) {
calc("",input,total);
}
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 8 years ago.
I cannot seem to be able to get this code to properly average numbers. When i input 5 numbers that are 1 digit such as 9, 6, 2 etc. it gives me incorrect results, such as putting in five 2's, it will give me the answer '0.0'. Even when inputting numbers with two or more digits it rounds the number incorrectly. Its like its not even recognising it as being a double. I think i am missing something extremely obvious, haven't programmed in a while so wouldn't be surprised.
Here is the code:
import java.util.*;
public class LittleBoxes2
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
int[] num;
double avg;
String cont = "Y";
while(cont.equals("Y") || cont.equals("y"))
{
num = new int [5];
for(int i = 1; i <= 5; i++)
{
System.out.println("Enter number " + i + ".");
num[i - 1] = input.nextInt();
}
avg = num[0] / 5 + num[1] / 5 + num[2] / 5 + num[3] / 5 + num[4] / 5;
System.out.println("The average number is: " + avg + ".");
System.out.println("Do you want to continue? (Y/N)");
input.nextLine();
cont = input.nextLine();
}
}
}
When both operands of / are integers, the division is integer division. You have:
avg = num[0] / 5 + num[1] / 5 + num[2] / 5 + num[3] / 5 + num[4] / 5;
This means, for example, 8 / 5 evaluates to 1, and 2 / 5 evaluates to 0. For your five 2's example this evaluates to:
= 2 / 5 + 2 / 5 + 2 / 5 + 2 / 5 + 2 / 5
= 0 + 0 + 0 + 0 + 0
= 0
You want, e.g.:
avg = num[0] / 5.0 + num[1] / 5.0 + num[2] / 5.0 + num[3] / 5.0 + num[4] / 5.0;
With that, one operand is a double, and so the num[n] integer operands are promoted to double, the division is floating-point division, and the result is a double.
double x = 4.0;
long y = 10;
byte z = 8;
char c = 'd';
System.out.println (y*++z / (z-- -6.0) + 'd'*0.5);
The result is 80.0, but I don't know why?
d is ASCII-Code Number 100.
First term is 80 second term is 2 third term is 50 ?
First term is 30, second is 50. Totals to 80.
'd' = 100
100 * 0.5 = 50
++z = 9
y * ++z = 10 * 9 = 90
z-- = 8, but after the operation. In the operation it is still 9
z-- - 6.0 = 9 - 6 = 3
90 / 3 = 30
30 + 50 = 80
Just break it into smaller pieces and it becomes clear why the result is 80.0.
public static void main(String[] args) {
double x = 4.0;
long y = 10;
byte z = 8;
char c = 'd';
System.out.println (y*++z); // this is 10 * 9 = 90
System.out.println ((z-- -6.0)); // this is 9 - 6 = 3
System.out.println ('d'*0.5); // this is 100 * 0.5 = 50.0
// System.out.println (y*++z / (z-- -6.0) + 'd'*0.5);
}
If you need a more rigorous treatment check this part of the JLS.
I think this question is about operator precedence
but also about widening conversions of the operands.
19 specific conversions on primitive types
are called the widening primitive conversions:
- byte to short, int, long, float, or double
- short to int, long, float, or double
- char to int, long, float, or double
- int to long, float, or double
- long to float or double
- float to double
(y ) * (++z) / ( (z--) - (6.0) ) + 'd' * 0.5
(10) * (++8) / ( (8--) - (6.0) ) + 'd' * 0.5 // z = 9
(10) * (9) / ( (9--) - (6.0) ) + 100 * 0.5 // z-- comes to 9--
(10) * (9) / ( (9) - (6.0) ) + 100 * 0.5
90 / ( 3.0 ) + 50
30.0 + 50
80.0