<?php // Formula: n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1. // Method 1. Using for loop $fact = 1; $number = 5; for ($i = 1; $i <= $number; $i++) $fact = $fact * $i; echo $fact; //---------------------------------- // Method 2: Using recursive method function factorial($n) { if ($n == 0) return 1; else return($n * factorial($n - 1)); } $number=6; echo factorial($number); ?>
Wednesday 19 November 2014
Simple Factorial Program in PHP
The factorial of a number is the product of all integers up to and including that number, so the factorial of 4 is 4*3*2*1= 24.
Tuesday 18 November 2014
Simple Prime number program in PHP
Que: What is Prime number?
Ans: A number is prime if it is divisible only by one and itself. (Ex: 2, 3, 5, 7, 11, 13, 17....etc)
Program:
Ans: A number is prime if it is divisible only by one and itself. (Ex: 2, 3, 5, 7, 11, 13, 17....etc)
Program:
<?php $num = 4; // <=== Replace desired number to check for ($i = 2; $i <= $num - 1; $i++) { if (bcmod($num, $i) == 0) { echo $num . " is not prime number :("; break; } } if ($num == $i) echo $num . " is prime number :)"; ?>
Fibonacci Series in PHP
Que: What is Fibonacci Series?
Ans: Numbers of Fibonacci sequence are known as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms, For example 8 = 3 + 5 (addition of 3, 5)
Fibonacci Series using for loop:
Fibonacci Series using recursion:
Output: 0 1 1 2 3 5 8 13 21 34
Ans: Numbers of Fibonacci sequence are known as Fibonacci numbers. First few numbers of series are 0, 1, 1, 2, 3, 5, 8 etc, Except first two terms in sequence every other term is the sum of two previous terms, For example 8 = 3 + 5 (addition of 3, 5)
Fibonacci Series using for loop:
<?php $term = 10; $num1 = 0; $num2 = 1; for ($i = 0; $i < $term; $i++) { if ($i <= 1) $result = $i; else { $result = $num1 + $num2; $num1 = $num2; $num2 = $result; } echo "<br>" . $result; } ?>
Fibonacci Series using recursion:
<?php function fibonacci($n) { if ($n == 0) return 0; else if ($n == 1) return 1; else return ( fibonacci($n - 1) + fibonacci($n - 2) ); } $term = 10; for ($i = 1; $i <= $term; $i++) { echo "<br>".fibonacci($c); $c++; } ?>
Output: 0 1 1 2 3 5 8 13 21 34
Subscribe to:
Posts (Atom)