I startet with a big solution containing a Bacteria class with age and 'liveOneDay' method, which seem to calculate correct numbers. But it also seemed to be running forever.
So I startet again with this little groovy script. The generations list contains the bacteria generations with 1,2,3 and 4 days old bacterias.
cache = dict()
# n is the number of days
def T(n):
if n <= 4:
return [1, 2, 4, 7, 11][n] # Base cases
elif n in cache:
return cache[n] # Speed things up with dynamic programming
return 2*T(n-1) - T(n-3)
amount = 0
day = 0
while amount < 1000000000000:
amount = T(day)
cache[day] = amount
day += 1
print(amount)
print(day)
At first I thought what can go wrong with objects. (Insert a warning BUZZ here)! Oh how wrong could have I been. While the object colony was striving and computing I was calculating the memory I needed... well, 1 TB would certanly be enough.
Then I had to use a similar approach that was already posted earlier :3
local current = {0, 1, 0, 0}
local i = 0
while true do
i = i + 1
current = {current[1] + current[2], current[1], current[2], current[3]}
--[[if i == 8 then
print(current[1] + current[2] + current[3] + current[4])
break
end
--]]
if current[1] + current[2] + current[3] + current[4] >= 1000000000000 then
print(i)
break
end
end
I guessed that the 'unique' bacterium wasn't going to be in the first 'day' of its cycle, and it turns out I was right on the first try, lol.
I used two Fibonacci sequences {1,2,3,5,8,13..}
First sequence is representing number of daily born (add to total living), and second sequence starts at the 5th day, and representing count of dead (subtract from total living).
import java.math.BigInteger;
public class Bacteria {
// Returns n-th Fibonacci number
static BigInteger fib( int n )
{
BigInteger a = BigInteger.valueOf( 0 );
BigInteger b = BigInteger.valueOf( 1 );
BigInteger c = BigInteger.valueOf( 1 );
for ( int j = 2; j <= n; j++ )
{
c = a.add( b );
a = b;
b = c;
}
return ( a );
}
public static void main(String[] args) {
BigInteger population = new BigInteger("0");
int day = 0;
BigInteger die = new BigInteger("0");
int count = 0;
do {
day ++;
population = population.add( fib(day) ).subtract(die);
if( day >= 5 ) {
count++;
die = die.add( fib(count) );
}
//System.out.println(population + " Day: " + day);
}while(population.compareTo( new BigInteger("1000000000000") ) < 0);
if(population.compareTo( new BigInteger("1000000000000") ) > 0){
day--;
}
System.out.println("Day: " + day);
}
}