Closed Thread Icon

Topic awaiting preservation: PHP and Big Numbers. (Page 1 of 1) Pages that link to <a href="https://ozoneasylum.com/backlink?for=30242" title="Pages that link to Topic awaiting preservation: PHP and Big Numbers. (Page 1 of 1)" rel="nofollow" >Topic awaiting preservation: PHP and Big Numbers. <span class="small">(Page 1 of 1)</span>\

 
Trigger
Paranoid (IV) Inmate

From: Wales
Insane since: Jun 2002

posted posted 05-02-2008 02:27

I'm trying to find the sum of all of the even terms in the Fibonacci series without exceeding four million here's my code.

code:
<?php
$first = 0;
$sum = 0;
$second = 1;
$n = 4000000;

for($i=1;$i<=$n-1;$i++)
   {
   $final = $first + $second;
   $first = $second;
   $second = $final; 
   if(($final % 2) == 0){  
     $sum = $sum + $final;
   }
   }

echo $sum;
?>




$sum returns INF. What gives? I'm assuming, the int type can't handle that much or given earlier output some how $sum is getting cast as float.

Any ideas how I can go about getting that elusive sum?

DL-44
Lunatic (VI) Inmate

From: under the bed
Insane since: Feb 2000

posted posted 05-02-2008 02:39

Don't know, but -

quote:
The size of an integer is platform-dependent


http://www.php.net/manual/en/language.types.integer.php

FWIW

Trigger
Paranoid (IV) Inmate

From: Wales
Insane since: Jun 2002

posted posted 05-02-2008 02:49

Yeah I got that, I tracked down the issue, The number int was overflowing, But that was just a sympton of my poor logic.

Instead of going through the series till I reached 4,000,000 I actually summed up all the even numbers of 4,000,000 entires of the series.

For the sake of thred compleition.

Here's the working code

code:
<?php
$first = 0;
$second = 1;
$sum = 0;
$n = 4000000;

 while($second < $n){
   $final = $first + $second;
   $first = $second;
   $second = $final;
   if(($final % 2) == 0){ 
     $sum = $sum + $final; 
   }
}

echo $sum;
?>




and the SUM? 4613732

Skaarjj
Maniac (V) Mad Scientist

From: :morF
Insane since: May 2000

posted posted 05-02-2008 13:01

Also, Trigger, it's good to note that you can condense (if I recall correctly, that is) "$sum = $sum + $final" into "$sum += $final"


Justice 4 Pat Richard

« BackwardsOnwards »

Show Forum Drop Down Menu