Task:

There are a couple of rabbits. She gives offspring (a new pair of rabbits) for the third month, and the following months - monthly. Children reaching three months begin to give birth. How many rabbits will be in a year?

What is wrong with this decision?

public class Test { public static void main(String[] args) { int a = 1; int b = 1; int n; int sum_fib; Scanner s = new Scanner(System.in); n = s.nextInt(); for (int i = 0; i < n; i++) { sum_fib = a + b; a = b; b = sum_fib; System.out.print(sum_fib + " "); } } } 

Closed due to the fact that it was off topic by Nicolas Chabanovsky ♦ Mar 7 '17 at 9:17 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Nicolas Chabanovsky
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • this is the third such question today, but with the code :) - Igor

1 answer 1

If I correctly understood the condition of the problem, then the sequence of the number of pairs is obtained as follows:

 1, 1, 1, 2, 3, 4, 6, 9, 13, 19, 28, 41, 60 

Where the first number is the number of pairs at the beginning of the first month, and then the number of pairs at the end of each month, up to and including the 12th.

If everything is so, and the answer is "120 rabbits" (60 pairs), then the Fibonacci sequence is not called. However, the linear recurrent sequence is still traced here. In particular:

F n = F n-1 + F n-3

Code to calculate:

 final int monthsCount = 12; int[] counts = new int[monthsCount + 1]; counts[0] = 1; counts[1] = 1; counts[2] = 1; for (int i = 3; i <= monthsCount; i++) { counts[i] = counts[i - 1] + counts[i - 3]; } System.out.println(Arrays.toString(counts)); 

The following was used as a “head on” solution and to check the results:

 private static class Pair { private static final int GET_MONTHS = 3; private int monthsCount = 0; public Pair inc() { monthsCount++; return (monthsCount >= GET_MONTHS) ? new Pair() : null; } } public static void main(String[] args) { ArrayList<Pair> pairs = new ArrayList<>(); pairs.add(new Pair()); for (int i = 0; i < monthsCount; i++) { List<Pair> newPairs = pairs.stream() .map(Pair::inc).filter(e -> e != null) .collect(Collectors.toList()); pairs.addAll(newPairs); } System.out.println(pairs.size()); }