writing a method for fibonacci sequence - java

I'm trying to write a for loop that calls the method fibonacci and prints the first 25 numbers in the fibonacci sequence. The problem is I'm a little confused about how to do that correctly. I'm a little confused about when the for loop in the run method calls the fibonacci method do the values inside the fibonacci method reset after reach pass of the for loop? So for example during the first pass of the for loop i = 0 and the values for int a and int b change inside the the fibonacci method. Do the values inside the fibonacci method reset on the next pass of the for loop?
import acm.program.*;
public class Fibonacci extends ConsoleProgram{
private void run(){
for(int i = 0; i <= 25; i++){
fibonacci(i);
println(fibonacci(i));
}
}
private int fibonacci(int n){
int n = 0;
int a = 0;
int b = 1;
while (n < 25);
int c = a + b;
a = b;
b = c;
}
return(a);
}

You're looping in two different places - run() and fibonacci(). Only one of these places should care about the loop, and the other should care about computing Fibonacci(n).
What we can do remove the loop from fibonacci, and only rely on the loop on the outside. Also, we're going to remove that statement int n = 0, since that shadows the parameter you're passing in.
Lastly, we're going to create two new static variables a and b, so that the values of those are preserved with this instance. If you don't do that, then you'd have to rely on either recursion or some other methodology to provide the appropriate values of a and b.
I'm not entirely sure why you need to extend ConsoleProgram, but I'll leave it in for now.
So, here's what it should look like.
public class Fibonacci extends ConsoleProgram {
static int a = 0;
static int b = 1;
public void run() {
for(int i = 0; i <= 25; i++) {
// Print the call to fibonacci(i) with every iteration.
}
}
private int fibonacci(int n) {
int c = a + b;
a = b;
b = c;
return c;
}
}

Fibonacci it's a typical example of an algorithm that can be easily approached with recursion, that's because:
you can divide the entire fibonacci sequence in steps,
in each step you have to do the same thing except for the final step where you got 0,
and the last step is "special" because 0 times any number gives you 0,
so if you apply the same step as before you simply nullify everything, this means that when your counter is 0 you have to do something different from your previous steps and it's:
multiply the result that you have stored by 1 and not by 0 ( or you can leave it as it is, it's the same thing as multiply by 1
exit the loop and terminate the fibonacci sequence
Internet is full of Fibonacci examples, 1 & 2 are more than enough for you.

The variables reset for each iteration of the loop. The variables a, b, and c are local variables that only "live" within the method. Every call to the fibonacci(n) method should start from the beginning of the fibonacci sequence and print out the terms up until the nth term. Therefore, while (n < 25); should not be part of the method. Also, int n = 0 resets n to zero, which is bad because we need to know what n is to get the nth term.
The ideal way to do this loop is:
private void fibonacci(int n) {
int i = 1; // a new variable i to count from the 1st term
int a = 0; // the first term
int b = 1; // the second term
while (i <= n) {
int c = a + b; // the new value for b
a = b; // switch the old a for the new a
b = c; // get the (i + 1)th term for the next iteration
System.out.println(a); // print out the ith term
i++;
}
}

You are not storing the returned int value of fibonacci();
int currentSum=0;
for(int i = 0; i <= 25; i++){
currentSum+=fibonacci(i);
println(currentSum);
}
and why do you have another variable n in your fibonacci(int n) ?
Please make sure first your fibonacci method is working. (The infinite while loop, etc.)
public static void main (String args[]){
for(int i = 0; i<25; i++) {
System.out.println(fibonacci(i));
}
}
static int fibonacci(int n){
if(n==0) {
return 0;
}
int a = 0;
int b = 1;
for(int i = 0; i < n; i++){
int temp = b;
b += a;
a = temp;
}
return(b);
}

Related

How do I count Iterations in loop and compare it to the iterations from the other class?

I wrote code that solves polynomials in two ways:
normal form a0x+a1x...an*x
Horner method.
Now, what I need, is to count the amount of multiplications in both classes and compare them. So, my program could decide in which case the Horner method is a better way to solve a polynomial. I couldn't find any ways to count the multiplicators myself.
static int count_2=0;
static int count_1=0;
//---------------------------------------------------------------------------//
public static double evalSimple(double[] a, double x) {
double y_temp = 0;
double y=0;
int n=1;
for(int i=1; i < a.length ; ++i) {
y_temp = (a[i] * Math.pow(x,n));
y = y + y_temp;
++n;
++count_1;
}
System.out.println(count_1);
return y+a[0];
}
//here would be the class to compare the amount of the multiplikations
I tried to initiate the variables count_1 & count_2 and put them in the for-loop, but I didn't get how to return the value (not just to print them in console) of them for the test environment.
A function can always return only one value. But you can make this a result object. I made the example with only one of your methods:
class Result {
double solution;
int iterations;
}
public static Result evalHorner(double[] a, double x) {
Result result = new Result();
for (int i = a.length - 1; i >= 0; i--) {
result.solution = a[i] + result.solution * x;
++result.iterations;
}
return result;
}
Also note that I did not use a global counter variable, so the returned value is fresh for the exact invocation.

Java method to get sum of int based on test logic

I am new to learning java and I have a written a method below. I am trying to understand how to satisfy the tester methods. Is there a way to get the correct logic with the while loop?
I stated that the sum = 0 and while the sum is less than i, increment the sum and loop till it reaches i then return the sum (or thats what i think that's what im trying to do) to satisfy the test. When i look at the junit error message for 1) it says its giving me 10 but expects 55, 2) says im getting 49 but expects 1225. 3) is satisfied. What am i doing wrong here? Is it possible to do this method either with an if statement or while loop?
public int sumOfInts(int i) {
int sum = 0;
while(sum < i)
++sum;
return sum;
}
public void testSumOfInts2() {
int sumOfInts = math.sumOfInts(10);
assertEquals(55, sumOfInts);
public void testSumOfInts3() {
int sumOfInts = math.sumOfInts(49);
assertEquals(1225, sumOfInts);
public void testSumOfInts4() {
int sumOfInts = math.sumOfInts(-49);
assertEquals(0, sumOfInts);
You are looking to make a method that gives you the cumulative sum. The method you have written just gives you the number of times it runs, which is exactly the number you have provided as argument.
You need to differentiate between the counter (the argument) and the cumulative sum, and also update the value of the counter so that the while loop knows when to exit.
Lastly, the <= comparison is necessary to get the correct value (vs just <).
Here is an example:
public int sumOfInts(int i) {
int sum = 0;
int counter = 0;
while(counter <= i) {
sum = sum + counter;
counter = counter + 1;
}
return sum;
}
Try this
public int sumOfInts(int i) {
int sum = 0;
int iteration = 0;
while(iteration < i){
sum = sum+iteration;
iteration++;
}
return sum;
}

How can I return the FIbonacci sequence using an int return type method without using recursion?

I'm trying to create a method in Java that prints the fib series up to the number passed to the method. My issue is that I'm required to use an int return type to return the series and I cannot use recursion.
My First Idea
My original idea was like shown. Which works just fine. It takes an argument of type int and returns void simply printing the numbers as they are calculated.
public void fibonacci(int num) {
int a = 0;
int b = 0;
int c = 1;
for (int i = 0; i < num; i++) {
a = b;
b = c;
c = a + b;
System.out.print(c + ", ");
}
}
What The Question Asks For
The code below shows what I was tasked to do. It asked for a method that takes an argument of type int and returns type int.
public int fibonacci(int num) {
//some code...
return x; //This is what confuses me. I know this isn't right.
}
To me this just seems impractical and maybe even impossible to use an int return type. I'm wondering if anyone knows a way this is possible.
Expected Output:
//Method call in driver class.
fibonacci(5);
//This would print to console.
1, 1, 2, 3, 5
You can use the equation [(h)^a - (j)^a] * [1/sqrt(5)].
'a' is fibonacci number wanted
'h' is [1 + sqrt(5)] / 2
'j' is [1 - sqrt(5)] / 2
public static int returnFibonacci(int a) {
double firstTerm; // calculate h
double secondTerm; //calculate j
double fib; //calculate 1/sqrt(5) with firstTerm and secondTerm
}

Loop never starting

I am trying to write a small method which will calculate the exponent given a number and power (I know about math.pow I am just doing this for kicks). However the loop inside my method never starts and I cant figure out why. My code is below, all help appreciated.
public static void main(String[] args) {
int result = exponantCalculation(2, 3);
System.out.println(result);
}
public static int exponantCalculation(int number, int power) {
for (int i = 1;i >= power;i++) {
number = number * number;
}
return number;
}
You've used the wrong comparison operator in the loop condition (>=, should be <= or < — see other answers).
Not sure, maybe this was intentional, BUT if the method is meant to calculate "number to the power of power", then you're incorrectly squaring the result of the previous iteration. This will produce a much higher value that the number to the power of power.
You need to introduce a new variable and multiply it with number in the loop, e.g.
long result = 1;
for (int i = 0; i < power; i++) {
result *= number; // same as "result = result * number"
}
return result;
Minor note: I've intentionally used long type for the result, which can slightly defer the integer overflow problem for big values.
Condition inside for loop is wrong.
Since you are passing 3 as power in your method as parameter, i is initialized with 1 and then condition gets checked whether i>=power with is obviously not true in this case so your loop never starts.
Change
for (int i = 1;i >= power;i++)
to
for (int i = 1;i <= power;i++)
if you wish to calculate the power of any number, you can use following method
public static int exponantCalculation(int number, int power) {
int result = 1;
for (int i = 1;i <= power;i++) {
result = result * number;
}
return result;
}
The for loop condition was wrong, but also you need to sotre the result in another variable:
public static int exponantCalculation(int number, int power) {
if(power == 0){
return 1;
}
int result = 1;
for (int i = 1;i <= power;i++) {
result *= number;
}
return result;
}

Is this a better way for Fibonacci Series with Recursion?

Where ever I see Recursive Fibonacci Series everyone tell that
a[i] = fib(i - 1) + fib( i - 2)
But it can also be solved with
a[i] = fib(i - 1) + a[i-2] // If array 'a' is a global variable.
If array 'a' is a global Variable, then a[i-2] will be calculated when it is calculating for a[i-2];
It can be solved with below program in java..
public class Fibonacci {
public static int maxNumbers = 10;
public static double[] arr = new double[maxNumbers];
public static void main(String args[])
{
arr[0] = 0;
arr[1] = 1;
recur(maxNumbers - 1);
}
public static double recur(int i)
{
if( i > 1)
{
arr[i] = recur(i - 1) + arr[i - 2];
}
return arr[i];
}
}
Further more, complexity is also less when compared with original procedure. Is there any disadvantage of doing this way?
You have done the first step for Dynamic Programming calculation of Fibonacci, idea of DP is to avoid redundant calculations, and your algorithm achieve its goal.
A "classic" Bottom-Up DP Fibonacci implementation is filling the elements from lower to higher:
arr[0] = 0
arr[1] = 1
for (int i = 2; i <= n; i++)
arr[i] = arr[i-1] + arr[i-2]
(Optimization could be storing curr,last alone, and modifying them at each iteration.
Your approach is basically the same in principle.
As a side note, the DP approach to calculate Fibonacci is taking O(n) time, where there is even more efficient solution with exponential of the matrix:
1 1
1 0
The above holds because you use the fact that
1 1 F_{n+1} 1*F{n+1} + 1*F{n} F_{n+2}
* = =
1 0 F_{n} 1*F{n+1} + 0*F{n} F_{n+1}
Using exponent by squaring on the above matrix, this can be solved in O(logn).
If you just want the nth fibonacci number you could do this:
static double fib(double prev, double curr, int n) {
if(n == 0)
return curr;
return fib(curr, prev+curr, n-1);
}
Initial conditions would be prev = 0, curr = 1, n = maxNumbers. This function is tail recursive because you don't need to store the return value of the recursive call for any additional calculations. The initial stack frame gets reused (which saves memory) and once you hit your base case the value that's returned is the same value that would be returned from every other recursive call.
By using an array like you do you only recalculate one of the two branches (the longest one in each iteration) ending up with a O(n) complexity.
If you were to keep track on how large fibonacci number you have caclulated earlier you can use that and produce O(max(n-prevn, 1)). Here is an altered version of your code that fills the array from bottom to i if needed:
public class Fibonacci {
public static final int maxNumbers = 93; // fib(93) > Long.MAX_VALUE
public static long[] arr = new long[maxNumbers];
public static int calculatedN = 0;
public static long fib(int i) throws Exception
{
if( i >= maxNumbers )
throw new Exception("value out of bounds");
if( calculatedN == 0 ) {
arr[0] = 0L;
arr[1] = 1L;
calculatedN = 1;
}
if( i > calculatedN ) {
for( int x=calculatedN+1; x<=i; x++ ){
arr[x] = arr[x-2] + arr[x-1];
}
calculatedN = i;
}
return arr[i];
}
public static void main (String args[]) {
try {
System.out.println(fib(50)); // O(50-2)
System.out.println(fib(30)); // O(1)
System.out.println(fib(92)); // O(92-50)
System.out.println(fib(92)); // O(1)
} catch ( Exception e ) { e.printStackTrace(); }
}
}
I changed double to long. If you need larger fibonacci numbers than fib(92) I would change from long to Biginteger.
You can also code using two recursive function but as the same value is calculating over again and again so all You can do a dynamic programming approach where You can store the value and return it where need.Like this one in C++
#include <bits/stdc++.h>
using namespace std;
int dp[100];
int fib(int n){
if(n <= 1)
return n;
if(dp[n]!= -1)
return dp[n];
dp[n] = fib(n-1) + fib(n-2);
return dp[n];
}
int main(){
memset(dp,-1,sizeof(dp));
for(int i=1 ;i<10 ;i++)
cout<<fib(i)<<endl;
}
This is only step from non recursive version:
https://gist.github.com/vividvilla/4641152
General this partially recursive approach looks incredibly messy

Categories

Resources