PHP Math Challenge

Sep 26, 2017 PHP
PHP Math Challenge

Hello Guys, I have been working on putting math challenges and their solution to learn and have fun with it. Check out some of the challenges as seen below.

Fibonacci problem

The Fibonacci sequence begins: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..
Given the formula f(n) = f(n-1) + f(n-2);
Write a function to find fibonacci sequence for given (n) number.

function fib($n) {
   return ( $n<=3 ) ? $n : (fib($n-2) + fib($n-1));
}

echo fib(5);

Print Patterns

Generate the multiplication table for given number.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

function pattern($n) {
	for($r = 1; $r <= $n; $r ++) {
		for($c = 1; $c <= $n; $c ++) echo ($r*$c). " ";
		echo "\n";
	}
}

pattern ( 5 );

Generate the following pattern.
*
**
***
****
*****

function pattern($n) {
    for($r=1; $r<=$n; $r++) {
	for($c=1; $c<=$r; $c++) { echo "*"; } // * until index
	echo "\n";
    }
}

pattern(5);

Generate the following pattern.
*
**
***
****
*****

function pattern($n) {
    for($r=1; $r<=$n; $r++) {
	for($c=$n-$r; $c>=0; $c--) { echo " "; } // n-1 space
	for($c2=1; $c2<=$r; $c2++) { echo "*"; } // * until index
	echo "\n";
    }
}

pattern(5);

Generate the following pattern.
*
***
*****
*******
*********

function pattern($n) {
	for($r = 1; $r <= $n; $r ++) {
		for($c = $r; $c <= $n; $c ++) echo " ";
		for($c2 = 1; $c2 <= (2 * $r) - 1; $c2 ++) {
			echo "*";
		}
		echo "\n";
	}
}

pattern(5);

Generate the following pattern.
*
*A*
*A*A*
*AAA*

function pattern($n) {
	for($r = 1; $r <= $n; $r ++) {
		$count=1;
		for($c = $r; $c <= $n; $c ++) echo " ";
		for($c2 = 1; $c2 <= $r; $c2 ++) {
			echo "*";			
			if($r > 1 && $count < $r){
				echo "A";
				$count++;
			}			
		}
		echo "\n";
	}
}

pattern(5);

Generate the following pattern.
1
232
34543
4567654
567898765

function pattern($n) {
	for($i = 1; $i <= $n; $i ++) {
		$num = $i;
		for($j = $i; $j < $n; $j ++) echo " ";
		for($k = 1; $k <= $i; $k ++) {
			echo $num;
			$num ++;
		}
		$num --; $num --;
		for($l = 1; $l < $i; $l ++) {
			echo $num;
			$num --;
		}
		echo "\n";
	}
}

echo pattern ( 5 );
Rate This Article

Tutorial on basic math challenges

2.50

About Author