I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me.
I'd do it this way:
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
This keeps it as close to your original Java code as possible.
[Editor's note: Integers have been replaced with ints. There is no reason to use Integers for this.]
The line
a, b = b, b+a
Doesn't easily translate. It's something like this. You could simplify it. This is the literal meaning.
t1 = b
t2 = b+a
a = t1
b = t2
You need to store the value of either a or b in a temporary variable first;
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
Java integers can only store the first 46 Fibonacci numbers, use a lookup table.
I'll just translate your earlier code:
public void fibb(int max) {
int a = 0;
int b = 1;
while (a < max) {
System.out.println(a);
int temp = a + b;
a = b;
b = temp;
}
}
Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid:
public int Fibb(int index) {
if (index < 2)
return 1;
else
return Fibb(index-1)+Fibb(index-2);
};
Given the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover.
The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this:
Make a list out of 'b' and 'a + b'
Make another list out of references to 'a' and 'b'
Assign all the elements from the second list to the first one
(It might actually be a tuple, I'm not exactly fluent in Python.)
So the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java.
In general, a statement in Python like
var1, var2, ...varN = expression1, expression2, ...expressionN
is going to translate in Java to
temp1 = expression1;
temp2 = expression2;
...
tempN = expressionN;
var1 = temp1;
var2 = temp2;
...
varN = tempN;
This way all the expressions resolve to values before the assignments happen, and none of the assignments have side effects on the expressions.
If I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible.
There was a recursive solution posted above, but this solution is tail recursive so it grows linearly.
public class Fibonacci {
public long fibonacci(int number) {
return fib(0,1,number);
}
private long fib(long result, long next, int n) {
if (n == 0)
return result;
else
return fib(next, result+next, n-1);
}
}
i'll do this
fib = 100;
for(int a = 1, b = 0;a <= fib;a += b, b = (a-b)) {
System.out.print(a + ",");
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
Is certainly wrong. I think switching the first two lines should do the trick
Related
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
}
I'm making a small program that determines the minimum integer of 3 integers. I'm having problems returning the integers back into the variable answer.
Here Is how I imagine the program working;
PROGRAM RUNS:
Looks for Method called "Minimumum" with the listed argument.
Determines the minimum integer and returns it back to the method Minimum
This value gets stored in the answer variable
Code:
public class Method {
public static void main(String[] args) {
int answer = Minimum(20, 40, 50);
}
public static int Minimum(int first, int second, int third) {
if ((first < (second) && (first < third))) {
return first;
} else if ((second < (first) && (second < third))) {
return second;
} else if (((third < first) && (third < second))) {
return (third);
} else {
System.out.println("error");
}
}
}
You need to return a result in all cases, so your else block is incorrect. Do you really think there is a fourth case ? No, there isn't : there are three integers so the minimum is one of those three, meaning there only are 3 cases... Simply remove the else block. By the way, why do you use so many parentheses ? It's useless, and unreadable.
public static int Minimum(int first, int second, int third){
if (first < second && first < third)
return first;
else if (second < first && second < third)
return second;
else
return third;
}
As noted by the others, this is not sufficient to make your method correct. Indeed, you don't care about strict inequality here because when two numbers are the same, you can choose either of them as the minimum. This code breaks if the two first parameters are equal. To fix it, simply use <= instead of < (everywhere).
Your code looks a bit complicated.
int Minimum(int first, int second, int third) {
int min = first;
if (second < min) {
min = second;
}
if (third < min) {
min = third;
}
return min;
}
This looks creepy, but it should do it.
Hope it helps to understand.
You have to return in your final else block. But you could simplify your code with Math.min(int, int). Something like,
public static int Minimum(int first, int second, int third) {
return Math.min(first, Math.min(second, third));
}
Minimum function should always return the integer value in any case. After else, add return statement.
In Java 8+ your method could also look as follows:
public static int minimum(Integer val1, Integer val2, Integer val3){
List<Integer> list = Arrays.asList(new Integer[]{val1, val2, val3});
return list.stream().min((Integer v1, Integer v2) -> v1 < v2 ? 0 : 1 ).get();
}
So I need to develop a method to find the smallest digit in an integer.
Here is my implementation
public int find(int n){
if(n < 10) return n;
return Math.min(n%10, find(n/10));
}
You can change the int by long ...
If you're interested in learning how to figure this out yourself (and you should be), I would try following these steps.
Do the process in your head, slowly - or even better, write the steps on paper! Take notice of each step you take.
Step one may be: look at the first digit
Consider the steps you've created. Are there parts which seem to be repeating themselves? These parts will likely be your recursive function.
Rewrite the steps as a recursive function (in plain English)
Translate the steps into your programming language; Java, in this case.
If you want, you can even leave the plain english steps in your code behind each line as comments, so everyone can easily follow your code
Personally I think a for loop would be quicker and easier than a recursive function. But for recursion or a for loop you need something to iterate on. Easiest way is to convert the number to a string and then iterate through it doing needed comparisons.
In your main:
int i = 578329;
String s = Integer.toString(i);
s = FindSmallest(s);
Call the function:
private String FindSmallest(String s){
if(s.length() <= 1)
return s;
String sFirstChar = s.substring(0,1);
String sSecondChar = s.substring(1,2);
int iFirst = Integer.parseInt(sFirstChar);
int iSecond = Integer.parseInt(sSecondChar);
if(iFirst < iSecond)
return FindSmallest( sFirstChar + s.substring(2));
else
return FindSmallest(sSecondChar + s.substring(2));
}
public static int find(int num) {
if(num < 10){
return num;
}
int d = num % 10;
int pmin = find(num / 10);
return (d <= pmin) ? d : pmin;
}
You can also write:
public static int minDigit(int n, int min){
if(n!=0) {
if(n%10 < min) {
min = n%10;
}
return minDigit(n/10, min);
}
return min;
}
I am busy on a parallel programming assignment, and I am really stuck. To be honest I am not entirely sure how each method works, but I think I have an idea.
I need to sum an array of consecutive values (in parallel). Seems easy enough, but I get 0 as an answer every time I try. I really don't know why.
class SumThreaded extends RecursiveTask<Integer> {
static int SEQUENTIAL_THRESHOLD = 10000;
double lo=0.0;
double hi=0.0;
long[] arr;
public SumThreaded(long[] array, double a, double b) {
arr=array;
lo=a;
hi=b;
}
public Integer compute() {
//System.out.println(mid);
if(hi - lo <= SEQUENTIAL_THRESHOLD) {
int ans = 0;
for(int i= (int) lo; i < hi; ++i)
ans += arr[i];
return ans;
}
else {
SumThreaded left = new SumThreaded(arr,lo,(hi+lo)/2.0);
SumThreaded right = new SumThreaded(arr,(hi+lo)/2.0,hi);
left.fork();
int rightAns = right.compute();
int leftAns = left.join();
return leftAns+rightAns;
}
}
public static void main(String args[]){
int size = 1000000;
long [] testArray=new long[size];
for(int i=0;i<size;i++){
testArray[i]=i+1;
}
SumThreaded t = new SumThreaded(testArray,0.0,testArray.length);
ForkJoinPool fjPool = new ForkJoinPool();
int result =fjPool.invoke(t);
System.out.println(result);
}
}
Any help would be greatly appreciated.
Your problem appears to be that you have two separate constructors for SumThreaded, only one of which sets the class's fields. When you're feeding in the long[] array from the new in sumArray, you throw the array away. You need to pick whether you're using ints or longs (and the sum of a big array is likely to need a long) and then make sure your values are getting set appropriately. Debugging and setting a breakpoint on compute would have shown you this.
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);
}