I have the following issue: when trying to add to a sum of BigIntegers the outcome remains 0.
Here is the code:
public void NumberOfOutcomes(int x, int y){
BigInteger first = BigInteger.valueOf(0);
BigInteger second = BigInteger.valueOf(0);
for(int i = 0; i <= (x / 2); i++){
first.add( fac(x - i).divide((fac(x - 2*i).multiply(fac(i)))) );
System.out.println("First " + first.add( fac(x - i).divide((fac(x - 2*i).multiply(fac(i)))) ));
}
for(int i = 0; i <= (y / 2); i++){
second.add( fac(y - i).divide((fac(y - 2*i).multiply(fac(i)))) );
System.out.println("Second " + second.add( fac(y - i).divide((fac(y - 2*i).multiply(fac(i)))) ));
}
System.out.println("First " + first);
System.out.println("Second " + second);
System.out.println(first.multiply(second));
}
Here fac is the factorial function.
Here is what comes on the terminal:
points1.NumberOfOutcomes(2, 3)
First 1
First 1
Second 1
Second 2
First 0
Second 0
0
This is because BigInteger is immutable which means that its value does not change. So first.add(x) will create a new BigInteger containing the computations result, i.e. just reassign the result to first, like first = first.add(...).
The add method of BigInteger class returns the sum of the operand and the value already stored in the the object itself. But it does not store the result in the object (first or second).
It doesn't work in the same way as
first += value;
actually, you have to make it look like this:
first = first.add(value);
Related
I want output like:
Dividend 1 : ...
Dividend 2 : ...
Dividend 3 : ...
Here is my code:
int i = 0;
while(i < dividendRates.length) {
System.out.println(String.format("Dividend %d : ", i) + (income * dividendRates[i]) );
i = i + 1;
}
But dividend number start with 0.
The easy way is just create new variable like 'int e = 1;' and use it, but I want to use variable 'i' and have output start with 1.
What should I do?
You can try the following code and I hope get the point:
int i = 1;
while( (i-1) < dividendRates.length) {
System.out.println(String.format("Dividend %d : ", i) + (income*dividendRates[i]) );
i = i + 1;
}
I am in a Java class and it's still early in the class. The assignment is to:
e^x Approximations
The value ex can be approximated by the following sum:
1 + x + x^2/2! + x^3/3! + …+ x^n/n!
The expression n! is called the factorial of n and is defined as: n! = 1*2*3* …*n.
Write a program that takes a value of x as input and outputs four approximations of ex done using four different values of n: 5, 10, 50, and 100. Output the value of x the user entered and the set of all four approximations into the screen.
Sample formula use: calculating e^7 using approximation with n = 5
1 + 7 + 7^2/2! + 7^3/3! + 7^4/4! + 7^5/5!
I've got all the rest to work, including getting n to be 5, 10, 50 and 100. I thought I had the factorial formula figured out and I used the number 4 like the sample we were show and my numbers done match. Could really use another set of eyes.
Here's my code with forumla (x is the value the user enters and n is the 5, 10, 50 and 100):
/**
* myFact takes in x and calculates the factorial
* #param x
* #param n
* #return the factorial as a long
*/
public static long myFact(int x, int n) {
//declare variables
long sum = x;
for (int i=2; i <= n; i++) {
sum += ((Math.pow(x, i))/i);
}
return (sum + 1);
}
}
Here's the main class where I am calling the function. The error I suppose could be there too:
public static void main(String[] args) {
//declare variable for user input and call method to initialize it
int x = getNumber();
long fact;
int n;
//Output first line
System.out.println("N\t approximate e^" + x);
for (n = 5; n <= 100; n *= 2) {
if (n == 10) {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
n += 15;
} else {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
}
}
}
Thanks for taking a look at this, it's taken me hours to get this as the teacher gave us very little help.
You did a mistake in
sum += ((Math.pow(x, i))/i);
here you need to calculate the i!. Add below method in your code
public static int fact(int i){
int fact = 1;
for (int n = i; n > 0; n--) {
fact = fact * n;
}
return fact;
}
Also change sum += ((Math.pow(x, i))/i) to
sum += ((Math.pow(x, i))/fact(i));
I'm currently learning Java and I've just beginned so my knowledge of it is not very good.
I have a problem with a program I wrote that calculates the first 100 values of the Fibonacci sequence. The point is that it just outputs the 2 and no other number.
This is the code of my program:
class MyClass1 {
public static void main(String[ ] args) {
int[] fib = new int[102];
fib[0] = 1;
fib[1] = 1;
int counter = 0;
int n1, n2, fibSum;
while(counter < (fib.length - 2)){
n1 = fib[counter];
System.out.println(fib[counter]);
counter++;
n2 = fib[counter];
System.out.println(n2);
counter++;
fibSum = n1 + n2;
System.out.println(fibSum);
fib[counter] = fibSum;
}
}
}
Thank you for your help.
There are some logical errors in your code.
First loop:-
Initially n1=fib[0]=1 and n2=fib[1]=1 and you print both. fib[2] is the sum and so it is 2. So far so good.
Second loop:-
n1 = fib[2] = 2. n2 = fib[3] = 0 and hence fib[4] = 2. This is where the problem happens. Hence you will always see 2 0 2 in the output from second loop onwards.
For Fibonacci sequence, you need to add the previous 2 values but you are only considering the previous value in your code. Here's a corrected version of your code:-
public static void main(String[ ] args) {
double[] fib = new double[100];
fib[0] = 1;
fib[1] = 1;
int counter = 2;
double n1, n2, fibSum;
System.out.println(fib[0]);
System.out.println(fib[1]);
while(counter < fib.length){
n1 = fib[counter-1];
n2 = fib[counter-2];
fibSum = n1 + n2;
System.out.println(fibSum);
fib[counter] = fibSum;
counter++;
}
}
Note that I am using type double because type int or even long is not enough for going upto the 100th term in this sequence.
Fibonacci number is the sum of the previous 2 numbers:
fibonacci(n) = fibonacci(n - 1) + fibonacci(n - 2)
So it can be evaluated very nice using recursion:
private static long fibonacci(int n) {
if (n <= 1) return n;
else return fibonacci(n - 1) + fibonacci(n - 2); }
public static void main(String[] args) {
int n = 102;
for (int i = 1; i <= n; i++)
System.out.println(i + ": " + fibonacci(i));
}
Your problem is that
A) all array values are initialized to 0
B) you are accessing "the next" array value, before assigning a value to it!
When you change your outputs to:
System.out.println("1. counter: " + counter + "/" + fib[counter]);
counter++;
n2 = fib[counter];
System.out.println("2. counter: " + counter + "/" + fib[counter]);
counter++;
fibSum = n1 + n2;
fib[counter] = fibSum;
System.out.println("3. counter: " + counter + "/" + fib[counter]);
You will find that it prints:
1 counter: 0/1
2 counter: 1/1
3 counter: 2/2
1 counter: 2/2
2 counter: 3/0
The last row shows you what is going on: you fetch the value at index 3 ... before you assigned a value to it. Therefore your whole fibonacci sum ... doesn't "start"; because you keep loosing values.
In other words: you have to ensure that your counter increases properly:
while(counter < (fib.length - 2)){
n1 = fib[counter];
System.out.println("1 counter: " + counter + "/" + fib[counter]);
n2 = fib[counter+1];
System.out.println("2 counter: " + counter + "/" + fib[counter+1]);
fibSum = n1 + n2;
fib[counter+2] = fibSum;
System.out.println("3 counter: " + counter + "/" + fib[counter+2]);
counter++;
}
Meaning: you need one full loop for each value of counter. When you run my solution, you will find that it works nicely (until counter hits 44/45 and we run into int overflow; as the numbers get too big).
After your first iteration you'll have the following values:
n1 = 1
n2 = 1
fibsum = 2
fib[2] = 2
All other values from fib[3] to length are uninitialized.
So in the second iteration :
n1 = 2
now the counter value will be increased by 1 which is counter = 3
n2 = fib[3]
// this one in not calculated properly and hence the issue.
public static void main(String[] args) {
int n = factorial(30);
int x = 0;
while (x <= 30) {
System.out.println(x + " " + n);
x = x + 1;
}
public static int factorial (int n) {
if (n == 0) {
return 1;
} else {
return n * factorial (n-1);
}
}
}
I'm trying to print out something like this:
0 1
1 1
2 2
3 6
4 24
...etc, up to 30 (30!)
What I'm getting instead is this:
0 (30!)
1 (30!)
...etc, up to 30
In words, I'm able to create the left column from 0 to 30 but I want to make it print the factorial of the numbers in the right hand column. With my code, it only prints the factorial of 30 in the right-hand column. I want it to print the factorials in order next to their corresponding number. How can I fix my code to do this?
This is pretty simple. Instead of defining a variable, you call the method with the updated x every time:
System.out.println(x + " " + factorial(x));
Note that your loop could be rewritten as a for loop, which is exactly what they're designed for:
for (int x = 0; x < 30; x++) {
System.out.println(x + " " + factorial(x));
}
Note a couple of things:
The x++. It's basically a short form of x = x + 1, though there are some caveats. See this question for more information about that.
x is defined in the loop (for (int x = ...) not before it
n is never defined or used. Rather than setting a variable that's only used once, I directly used the result of factorial(x).
Note: I'm actually pretty certain that an int will overflow when confronted with 30!. 265252859812191058636308480000000 is a pretty big number. It also overflows long, as it turns out. If you want to handle it properly, use BigInteger:
public BigInteger factorial(int n) {
if (n == 0) {
return BigInteger.ONE;
} else {
return new BigInteger(n) * factorial(n - 1);
}
}
Because of BigInteger#toString()'s magic, you don't have to change anything in main to make this work, though I still recommend following the advice above.
As #QPaysTaxes explains, the issue in your code was due to computing the final value and then printing it repeatedly rather than printing each step.
However, even that working approach suffers from a lack of efficiency - the result for 1 computes the results for 0 and 1, the result for 2 computes the results for 0, 1, and 2, the result for 3 computes the results for 0, 1, 2, and 3, and so on. Instead, print each step within the function itself:
import java.math.BigInteger;
public class Main
{
public static BigInteger factorial (int n) {
if (n == 0) {
System.out.println("0 1");
return BigInteger.ONE;
} else {
BigInteger x = BigInteger.valueOf(n).multiply(factorial(n - 1));
System.out.println(n + " " + x);
return x;
}
}
public static void main(String[] args)
{
factorial(30);
}
}
Of course, it would be faster and simpler to just multiply in the loop:
import java.math.BigInteger;
public class Main
{
public static void main(String[] args)
{
System.out.println("0 1");
BigInteger y = BigInteger.ONE;
for (int x = 1; x < 30; ++x) {
y = y.multiply(BigInteger.valueOf(x));
System.out.println(x + " " + y);
}
}
}
Just for fun, here's the efficient recursive solution in Python:
def f(n):
if not n:
print(0, 1)
return 1
else:
a = n*f(n-1)
print(n, a)
return a
_ = f(30)
And, better still, the iterative solution in Python:
r = 1
for i in range(31):
r *= i or 1
print(i, r)
I couldn't figure out how the decrement operator (e--)
works in code below, so i wrote the other class below it
to get the same result. I want to know how the decrement operator
achieves that result in the Power class. - Newbie.
int result, e;
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);
}
Code written to achieve same result
int result = 1;
for(int i=0; i < 10; i++) {
if (i > 0) {
result*=2;
}
System.out.println("2 to the " + i +
" power is " + result);
}
So the first example is resetting result for each iteration of the main for loop, so it needs to recalculate from scratch each time, where as the second example is keeping the previous computed value. The if in the second example is not needed is it.
The decrement operator modifies the variable on which it's called. So e-- is effectively e = e - 1 (except the overall result of the expression is different, see below).
This code:
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
starts with result = 1 and then loops for i iterations doubling the value in result. Equivalent code using for which you seem more comfortable with:
result = 1;
for (e = 0; e < i; e++) {
result *= 2;
}
There are two forms of the decrement (and increment) operator: Prefix and postfix, depending on whether the operator is before (prefix) or after (postfix) its operand. Either could be used in the code you were asking about, because the only difference is the result of the expression.
Prefix: Suppose we have x = 5. The expression --x has the value 4: First we decrement x, then we take its new value as the result of the expression.
Postfix: Suppose we had x = 5 (again). The expression x-- has the value 5, with x ending up containing 4: First we grab the current value of x as the result of the expression, then we decrement it (because the -- is after x).
int x, r;
x = 5;
r = --x; // Prefix
System.out.println("r = " + r + ", x = " + x); // "r = 4, x = 4"
x = 5;
r = x--; // Postfix
System.out.println("r = " + r + ", x = " + x); // "r = 5, x = 4"
i figure out that by placing a System.out.println(e) i could "see" the variable "e" behavior in order to make sense of the decrement.
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) {
System.out.println(e); // not part of the original program
result *= 2 ;
e--;
System.out.println(e); // not part of the original program
}
//System.out.println("2 to the " + i +
//" power is " + result);
}
This is the output:
C:\Users\enrique\Desktop\Hello.java>java Power: 1, 0, 2, 1, 1, 0, 3
e = 1(iteration 1), 2^1, e (1) decremented to 0, e = 2 (iteration 2), 2^2, e(2) decremented to 1, e = 1 re-enter The while but is ignored as 2^1 is already registered, e (1) decremented to 0, e = 3 (iteration 3), 2^3…