Does anyone know how to work this out? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
What output is produced by the following program?
The answer says 7 but i have trouble working it out.
public class practice {
public static void main(String[] args){
int i = 5;
int b = g(i);
System.out.println(b+i);
}
public static int f(int i) {
int n = 0;
while (n * n <= i) {n++;}
return n-1;
}
public static int g(int a) {
int b = 0;
int j = f(a);
b = b + j;
return b;
}
}

I assume main is getting called. Here is a list of steps that happen
g gets called with 5 as its parameter.
then in function g, f gets called with g's parameter, which is 5
In function f n is set to zero, a while loop is called and every time n*n is less than or equal to its parameter, which is 5, n is incremented. below outlines the while loop.
0*0 is less than 5, increment n from 0 to 1 and continue.
1*1 is less than 5, increment n from 1 to 2 and continue.
2*2 is less than 5, increment n from 2 to 3 and continue.
3*3 is not less than 5, break out of the loop.
n-1, which is 3-1=2, gets returned back to where it was called, in variable j in function g.
b gets assigned to b+j which is 0+2.
b gets returned back to variable b in function main.
b+i, which is 5+2, which is 7, gets printed as the answer.

Your using a number (5) and basically checking what is the first whole number squared that equals more than than 5. Then you negate 1 from the answer and add 5.
So here is the maths:
1. Find the first whole number squared that is larger than 5
0*0 = 0 //+1
1*1 = 1 //+1
2*2 = 4 //+1
3*3 = 9 //3*3 is the first value over 5; loop breaks
2. Negate 1 from 3 (the first whole number when squared that is larger than
3 - 1 = 2; //using 3, negate 1 (also could have used n--)
3. Using the final value 2 add 5
2 + 5 = 7 //using 2 add 5
Answer is 7.
There is some really unnecessary stuff in this code, such as the two extra methods.

Related

Java while loop nested in a for loop.

I have this simple code sample that I don't understand.
// Compute integer powers of 2.
class Power {
public static void main (String args[]) {
int e, result;
for (int i = 0; i < 10; i++) {
result = 1;
e = i;
while (e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
}
Producing this output.
2 to the 0 power is 1
2 to the 1 power is 2
2 to the 2 power is 4
2 to the 3 power is 8
2 to the 4 power is 16
2 to the 5 power is 32
2 to the 6 power is 64
2 to the 7 power is 128
2 to the 8 power is 256
2 to the 9 power is 512
Questions:
How come result is not always 2, since it's being re-initialized every time the for loop is entered?
The e-- decrement doesn't do a thing either, does it? Since, again, e is being set equal to i afresh on every iteration.
Thanks.
How come result is not always 2, since it's being re-initialized every
time the for loop is entered?
Yes, it is being re-initialized but only in the first loop. Your inner loop is looping while(e > 0) and double result at each iteration. Then once you are done looping, you pring the result and restart. The value of result will depend on e which define the number of times result is doubled.
The e-- decrement doesn't do a thing either, does it? Since, again, e
is being set equal to i afresh on every iteration.
Again, yes it is being set back to i at each iteration but that doesn't mean it is useless. At each iteration, e is set back to the new value of i, and then you use it to create an inner loop while e > 0 where at each iteration you decrement e of 1 and double the result.
The two questions kind of go together.
You see, e is set to i which is actually INCREASED each iteration.
And the higher e is, the more often the inner while will be worked through.
So for example in your 3rd for iteration
i = 2
e = 2
result = 1
So first while:
result = result*2 = 1*2 = 2
e = 1
e is still > 0 so after the second while:
result = result*2 = 2*2 = 4
e = 0
And there we go.
e-- did something twice and result is NOT 2.
result and e are re-initialized at the top of the for loop, but are modified within the while loop before result is displayed at the bottom of the for loop.

Integer powers program Java help needed

So i was getting this program in my book and tested it, it worked fine. I need help though understanding how it excactly works. I know the power of two means for example 2x2x2x2x2x2x2x2x2 = 512. Well, here is the program:
// Compute integer powers of 2.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i + " power is " + result);
}
}
}
So i've learned that result *=2 means: result = result * 2. I don't get how this works. Example, i is now 4. Result = 1 again, e=i, so e is now 4. 4 is higher than 0, so the while loop runs. Then it say's result is result * 2, but that's 1=1 * 2 = 2. But the result should be 16. How does result changes here to 16? Because it is 1 all the time. I don't get it. Also, why the e-- part? I've tried the program with e++, but then it prints result as 1 and after this only 0. Also tried it without e-- or e++ at all, but then it freezes in the dos-prompt. Please note that i am a beginner and this is my first while loop. Any help i would appreciate.
while(e > 0) {
result * = 2;
e--;
}
this loop executes untill the e becomes zero.
so in first loop
result = 1 * 2;
in second loop
result = result * 2; means result = 2 * 2
likewise.
You are using nested loops. That is, a while loop inside a for loop. This means that for every iteration of for loop, while loop will execute until it's condition becomes false.
Now coming to your questions, for first iteration of for, i = 0. Which means that e = 0, which in-turn means that while loop will not execute. So, result is 1 here, which is logical since any n^0 = 1.
For second iteration of for, i = 1. Which means that e = 1. Here, while loop will run for 1 iteration. It will make result = 2 (result *= 2). So, result is 2 because 2^1 = 2.
Below is the dry-run table.
for i while e result
loop loop
1 0 1 0 1
2 1 1 1 2
3 2 1 2 2
1 2 1 4
4 3 1 3 2
2 2 2 4
1 3 1 8
and so on. This table seems ugly, but it will give you a hint.
How does result changes here to 16? Because it is 1 all the time.
Result is only initialized with 1, but it's value is multiplied each time while loop executes.
I've tried the program with e++, but then it prints result as 1 and
after this only 0.
If you put e++ instead of e--, this loop will run until e overflows. But as soon value of e reaches 33, result will become 0 due to multiplication. And after that, it will remain 0.
Also tried it without e-- or e++ at all, but then it freezes in the
dos-prompt.
It means that your condition of while loop will never become false, and hence, it will be an infinite loop.

Learning Java - Do not fully understand how this sequence is calculated (Fibonacci) in for loop [duplicate]

This question already has answers here:
Java recursive Fibonacci sequence
(37 answers)
Closed 8 years ago.
I am learning Java and I have this code from the internet and running it in Eclipse:
public class Fibonacci {
public static void main (String [] args) {
for (int counter = 0; counter <= 3; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
I've tried to understand it but cannot get it. So I run through the code and counter gets passed in through the fibonacci method. As counter starts at 0 and this is what gets passed first, then 1 and I understand the method passes back 0 and then 1.
When it reaches 2: it will return 2-1 + 2-2 = 2 and it does return this.
When it reaches 3: it will return 3-1 + 3-2 = 3 but it does not return 3 it returns 2.
Please can someone explain to me why as I cannot figure this out?
Thanks
First, I have to tell you that this recursive version has a dramatic exponential cost. Once you understand how it works, my advice for you would be to learn about tail recursivity, write a tail-recursive solution, an iterative solution, and compare them to your current method for high values of "number".
Then, your function basically uses the mathematical definition of the Fibonacci sequence :
f0 = 1, f1 = 1, fn = fn-1 + fn-2 for all n >= 2
For example if we call fibonacci(3), this will return fibonacci(2) + fibonacci(1). fibonacci(2) will be executed first and will return fibonacci(1) + fibonnacci(0). Then fibonacci(1) will return immediately 1 since it is a terminal case. It happens the same thing with fibonnacci(0), so now we have computed fibonnacci(2) = 1 + 0 = 1. Let's go back to fibonacci(3) which has been partially evaluated at this point : 1 + fibonnacci(1). We just have to compute fibonnacci(1) and we can finally return 1 + 1 = 2.
Even in this little example, you can see that we evaluated twice fibonacci(1), that is why this version is so slow, it computes many times the same values of the sequence, and it gets worth when "number" is high.

Project euler 10 help. Whats wrong with this code? the sum flips to negative [duplicate]

This question already has answers here:
How does Java handle integer underflows and overflows and how would you check for it?
(12 answers)
Closed 8 years ago.
// finding sum of all primes under 2 million
public class lll {
public static void main(String[] args) {
int a = 2;
int b = 0;
int c = 0;
while (a < 2000000) {
int i = 1;
for (i = 1; i * i <= a; i++) {
if (a % i == 0)
//if factor is found of number a b goes up 1
{
b++;
}
}
// all primes have only one factor <= sqrt (1)
if (b == 1)
// if b =1 , a is prime so c+=a
{
c += a;
}
//reset b and add one to a to move on
b = 0;
a++;
// for error checking see description
System.out.println(c);
}
System.out.println(c);
}
}
Im trying to make a code to find the sum of all primes under 2 million, heres what i have it gives 1179908154, but this is not right, c is supposed to be the sum. I tried getting c after every check of number being prime and it shows that during the running of this code it lips from positive to negative and then back again. it makes no sense a starts at 1, a goes up c starts at 0, it goes up by a so how is c getting negative (a is never negative), please help me, I have managed to used this method of prime checking to correctly get the 10001st prime, it worked then.
A 32 bit integer can only hold numbers below about 2 billion. If you try to add more to that number (accessible by Integer.MAX_VALUE), you will end up "flipping" to negative numbers. Try out the following code:
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
So your problem is that integers aren't big enough! How can you solve this? The simplest way is to use a long instead of an int. Hypothetically, what if a long isn't even big enough? Then you can use a class like BigInteger, which isn't constrained to a fixed number of bits, and can grow as necessary.
Well, you declared c as an int which in java has a max value of 2,147,483,647 . The sum of all primes less than 1 million is 37,550,402,023, so Im thinking you are surpassing the data storage for int which is why its flipping negative on you.
My guess is that it has something to do with memory. In java the maximum number an integer can hold is 2147483647. So if the sum of primes goes over this number, it will loop back to -2147483648 and continue counting. Try making your variable c a long instead.

I don't know why my variables are getting these values [duplicate]

This question already has answers here:
Java: Prefix/postfix of increment/decrement operators
(11 answers)
Closed 9 years ago.
public int Gauss_Jordan(double[][] matrix, int numOfRows, int numOfCols) {
for (int col_j = 0; col_j<numOfCols; col_j++) {
row_i = nonzeros ++;
System.out.println(row_i+" and "+nonzeros);
}
//return matrix;
return 0;
}
up above in the method called "Gauss_Jordan", you can see a for loop where it iterates until a certain condition is met. (duh.. lol sorry).
so i set row_i = nonzeros++ but here's the thing, when I print out each iteration i get
0 and 1,
1 and 2,
2 and 3
. I would expect the output to be:
1 and 1,
2 and 2,
3 and 3.
How come this is not the case?
You'd need ++nonzeros instead of nonzeros++ to get what you expect.
Thats called post-increment;
When you say row_i = nonzeros ++;
first the row_i will get assigned with the value of nonzeros and the nonzero will get incremented.
try pre-increment
row_i = ++nonzeros;
If pre-increment is not what you wanted. Check the initialization of nonzeros and change it into '1` for it to show up as you want. Your codes are functioning as they should.

Categories