public class program { public static void main(string[] args) { int lastfibo = 1; // added check if last fib calculated on 4000000 (int = 3; lastfibo <= 4000000; = + (i - 1)) { lastfibo = fibo(i); } } public static int fibo(int i) { int total = 0; if (i % 2 == 0) { total += i; return total; } return total; } } the purpose of code print sum of numbers in fibonacci sequence who's values less 4 million. using recursion code returns stack overflow error recommended iterate through numbers. difficulty encountered knowing how print "total" variable. scope articles basic , creating static int total = 0 return 0.
first, pointed out comments: loop not iterate fibonacci sequence. second, variable total exists in scope of fibo method. every time method called, total starts value 0.
use correct fibonacci algorithm , add return value of fibo method calculate sum:
public class program { public static void main(string[] args) { int total = 0; int previousvalue = 0; int currentvalue = 1; while (currentvalue < 4_000_000) { int nextpreviousvalue = currentvalue; currentvalue += previousvalue; previousvalue = nextpreviousvalue; total += fibo(currentvalue); } system.out.println(total); } public static int fibo(int i) { if (i % 2 == 0) { return i; } return 0; } } 4_000_000 integer literal can use since java 7 number 4000000. purpose of underscores make better readable humans. programmatically there no difference using 4000000. details see primitive data types in java tutorials.
Comments
Post a Comment