0 Replies - 1377 Views - Last Post: 16 July 2011 - 01:28 PM

#1 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3796
  • View blog
  • Posts: 13,742
  • Joined: 08-August 08

Yet another Fibonacci solution!

Posted 16 July 2011 - 01:28 PM

Description: Run as you would any other PHP script! Set the number of digits by changing the value of $most_digits in line #6.This snippet calculates the Fibonacci series up to a specified number of digits. It uses vectors to keep track of all of the digits in each number in the series and does the addition "manually" as you would with pencil and paper.


There is a slight difference in where these two snippets stop calculating Fibonacci numbers. Neither currently calculates the last number of the given number of digits. I'll leave that for interested readers to adjust.
<?php
$digits = array();
$digits[0] = array(0);
$digits[1] = array(1);
$digits[2] = array(0);
$most_digits = 25;

while(count($digits[0]) <= $most_digits) {
	pad($digits[0], count($digits[1]));
	show_num($digits[0]);
	add_digits($digits);
}

function add_digits(&$dg) {
	$max = count($dg[1]);
	pad($dg[0],$max);
	$carry = 0;
	for($i = 0; $i < $max; $i++) {
		$dg[2][$i] = $dg[0][$i] + $dg[1][$i] + $carry;
			if($dg[2][$i] > 9 ) {
				$dg[2][$i] -= 10;
				$carry = 1;
			} else { 
				$carry = 0;
			}
			if($i+1 == $max && $carry) {
				$max++;
				pad($dg[0],$max);
				pad($dg[1],$max);
			}
		}
	array_shift($dg);
}

function show_num($nm) {
	$max = count($nm);
	$st = "";
	$highest_order = false;
//	for($i = 0; $i < $max; $i++) {
	for($i = $max-1; $i >= 0; $i--) {
		if($highest_order || $nm[$i] > 0) {
			$st .= $nm[$i];	
			$highest_order = true;
		}
	}
	if(!$highest_order) {
		$st = "0";
	}
	echo $st."
";
}

function pad(&$dg, $num) {
	while(count($dg) < $num) {
		$dg[] = 0;
	}
}
?>


Is This A Good Question/Topic? 0
  • +

Page 1 of 1