I want to know how to print factorial in php. I have try to search on Google but unable to find result with solid prove example (Php Code). I find this forloop, i'm not satisfy with this.
for($c=3; $c>=1;$c--){
for($d=$c; $d>=1; $d--){
echo $c;
}// for ends
echo "<br />";
}// for ends
Out Put 333 22 1
I want this printed as output:
5 * 4 * 3 * 2 * 1
For calculating factorial,
function factorial($in) {
return array_product(range(1, $in));
}
and use it like,
echo factorial(5);
If you want to print factorial,
function factorial_print($in) {
return implode(' * ', array_reverse(range(1, $in)));
}
and use it like,
echo factorial_print(5);
Calculating a factorial is pretty straightforward, and doesn't need recursion either:
function factorial($x) {
$r = 1;
for ($i = 2; $i <= $x; ++$i) {
$r *= $i;
}
return $r;
}
echo factorial(10), PHP_EOL;
Try this one
function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * factorial($number-1));
}
}
Use following function inbuilt in PHP.
$fact1 = gmp_fact(5); // 5 * 4 * 3 * 2 * 1
echo gmp_strval($fact1) . "\n";
For more refer HERE
Related
I am trying to make a simple while loop using a class to get the factorial of a number. However, for some reason, the while loop is only returning the value after it has run once.
Here is my code:
<?php
class Factorial {
public function calculate($int){
$intStep = $int-1;
do {
$int*=$intStep;
$int--;
return $int;
} while($int>0);
if (!is_int($int)){
echo "entry is not a number";
}
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
I see a number of problems with your code:
return $int; is run inside the do while loop, which means it'll only ever run once.
You're decrementing $int instead of $intStep
You're checking if $int is below zero instead of $intStep
Here's your code with all of these problems fixed, it works and returns 15:
class Factorial {
public function calculate ($int) {
if (!is_int($int)) {
echo "entry is not a number";
}
$intStep = $int - 1;
do {
$int += $intStep;
$intStep--;
} while ($intStep > 0);
return $int;
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
3v4l.org demo
You shouldn't return from your function until your result is ready. Since you return early, you won't finish your calculation.
In general, your life will be easier if you learn how to debug. For PHP, the easiest way would be to echo stuff throughout your code. If you put echo $int inside of your loop it would be more obvious to you what the issue was.
try this
<?php
class Factorial {
public function calculate($num){
$Factorial = 1;
$i =1;
do{
$Factorial *= $i;
$i++;
}while($i<=$num);
return $Factorial;
}
}
$factorial = new Factorial;
echo $factorial->calculate(5);
?>
Factorial ? Maybe the following code is what you want:
Don't forget negative Numbers.
class Factorial {
public function calculate ($int) {
if (!is_int($int)) {
echo "entry is not a number";
}
if ($int == 0 || $int == 1) {
$result = 1;
} else if ($int < 0) {
$result = $this->calculate($int + 1) * $int;
} else {
$result = $this->calculate($int - 1) * $int;
}
return $result;
}
}
$factorial = new Factorial;
echo $factorial->calculate(-4);
I need to round the returned number to closest multiple of 5 in this PHP.
return number_format(($entry['69']*$entry['68.2']*0.7), 0, ".", ",").'€' ;
How to get it correctly?
You can use round($val/5)*5:
$val = round($entry['69'] * $entry['68.2'] * 0.7 / 5) * 5;
return number_format($val, 0, ".", ",").'€' ;
Here is a custom function with greater detail of how everything is happening. You can change anything here if you need to update your code.
<?php
//Enter your code here, enjoy!
function roundClosest($num){
$helpVar = round($num/5);
$helpVar2 = $helpVar * 5;
if($num - $helpVar2 > 2.9){
$res = ($helpVar + 1) * 5;
}
else{
$res = $helpVar * 5;
}
return $res;
}
echo roundClosest(62.34);
echo "\n";
echo roundClosest(63.67);
Output:
60
65
Hope this helps!
I am writing a program to sum the digits of a number , it is working fine for small numbers but for large no it is giving unexpected sum?
below is the program.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
class demo {
private $sum = 0;
private $num = 0;
private $rem = 0;
public function digit_sum($digit) {
//echo gettype($digit).'<br>';
try {
if (gettype($digit) == 'string') {
throw new Exception($digit . ' is not a valid number <br>');
} else {
$this->num = $digit;
while ($this->num > 0) {
$this->rem = $this->num % 10;
$this->sum = $this->sum + $this->rem;
$this->num = $this->num / 10;
}
return "Sum of no $digit is = " . $this->sum . '<br>';
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
$sum = new demo();
echo $sum->digit_sum('sfsdfsdfds');
echo $sum->digit_sum(12345);
// outputs correct sum
echo $sum->digit_sum(3253435674);
//outputs incorrect sum
i see the above code results fine for integer no but not for double no'
please guide me what will be the perfect solution to this problem?
Do you know if you put a new echo $sum->digit_sum(32); The output will show you 62. Cause you create object once and call the same function multiple times. The object stores the sum for all the times.
Solution:
Just put an statement $this->sum = 0; before the while loop to clear the previous sum.
Online Example: https://3v4l.org/C7Yli.
Update: I tested the scripts in writephponline.com as per your comment and get the following result.
I want to create a function in which I put two values (value and its power - Example function: multiply(3, 3) result 27). I have tried so far but failed, I have searched using Google but I have been unable to find any result because I don't know the name of this function.
What I want exactly:
3,3 => 3 x 3 x 3 = 27
4,4 => 4 x 4 x 4 x 4 = 256
What I tried:
function multiply($value,$power){
for($x = 1; $x <= $value; $x++ ){
return $c = $value * $power;
}
}
echo multiply(3,3);
The answer has already been accepted, but I had to come here and say that all answers here use a bad algorithm. There are better ones. Including very simple ones, like exponentiation by squaring that reduces the complexity from O(power) to O(log(power)).
The idea is to square the base while dividing the exponent by 2. For example
3^8 = 9^4 = 81^2 = 6561
There is a special case when the exponent is odd. In this case, you must store a separate variable to represent this factor:
2^10 = 4^5 = 16^2 * 4 = 256 * 4 = 1024
PHP isn't one of my strong skills, but the final algorithm is as simple as:
function multiply($value, $power){
$free = 1;
while ($power > 1) {
if ($power % 2 == 1)
$free *= $value;
$value *= $value;
$power >>= 1; //integer divison by 2
}
return $value*$free;
}
echo multiply(3, 3) . "\n";
echo multiply(2, 10) . "\n";
echo multiply(3, 8) . "\n";
Oopsika, couldn't have asked a more obvious question. Use the built-in function named pow (as in a lot of languages)
echo pow(3, 3);
Edit
Let's create our own function.
function raiseToPower($base,$exponent)
{
// multiply the base to itself exponent number of times
$result=1;
for($i=1;$i<=$exponent;$i++)
{
$result = $result * $base;
}
return $result;
}
function exponent($value,$power)
{
$c=1;
for($x = 1; $x <= $power; $x++ )
{
$c = $value * $c;
}
return $c;
}
If you have PHP >= 5.6 you can use the ** operator
$a ** $b Exponentiation Result of raising $a to the $b'th power.
echo 2 ** 3;
If you have PHP < 5.6 you can use pow:
number pow ( number $base , number $exp )
echo pow(2, 3);
Your own function is:
function multiply($value, $power) {
$result = 1;
for($x = 1; $x <= $power; $x++){
$result *= $value;
}
return $result;
}
echo multiply(3,3);
Read more at:
http://php.net/manual/en/language.operators.arithmetic.php
http://php.net/manual/en/function.pow.php
Just try to run this code I hope your problem will be solved.
If you defining any function then you have to call it return value.
<?php
function multiply($value,$exp)
{ $temp=1;
if($exp==0)
return $temp;
else
{
for($i=1;$i<=$exp;$i++)
$temp=$temp*$value;
return $temp;
}
}
echo multiply(5,6);
?>
echo "Enter number (will be mutiplied):".PHP_EOL;
$value = (int) readline("> ");
echo "Enter number for multiplier:".PHP_EOL;
$multiplier = (int) readline("> ");
function power(int $i, int $n):int {
$result =1;
for ($int = 1; $int < $n; $int++){
$result *= $i;
}
return $result;
}
echo power($value,$multiplier);
Is it possible to change this code into function without using a loop?
$start = 80;
for ($i = 1; $i <= 10; $i++) {
$start = $start * 1.5;
echo "level ".$i.": ".$start."<br>";
}
function generate($start, $level){
// some code
return $start;
}
For level 1 you have:
$start = $start * 1.5;
For level 2 $start is result from level 1, so:
$start = ($start * 1.5) * 1.5;
This same as
$start = $start * 1.5 * 1.5;
And can be simplified to
$start = $start * pow(1.5, $level);
In the end your function should look like:
function generate($start, $level){
return $start * pow(1.5, $level);
}
if you want to get the same result(include the level print to screen) you can use this code:
function generate2($start, $from,$to){
if($from==$to+1)
return 1.5;
$tmp=$start*1.5;
echo "level ". ($from).": ".$tmp."<br>";
return 1.5*generate2($tmp,$from+1,$to);
}
Or this:
<?php
define ("MAX_LEVEL",10) ;
function generate($start, $level)
{
if($limit==0)
return 1.5;
$tmp=$start*1.5;
echo "level ". (MAX_LEVEL-$level+1).": ".$tmp."<br>";
return 1.5*generate($tmp,$level-1);
}
Here some check code:
$start = 80;//<=================your code
for ($i = 1; $i <= 10; $i++) {
$start = $start * 1.5;
echo "level ".$i.": ".$start."<br>";
}
echo"---------------------------- <br>";
generate(80,10);//<====================my code
echo"---------------------------- <br>";
generate2(80,1,10);
?>
if you not need the prints you can use very simple function:
function generate($start, $level){
return $start * pow(1.5, $level);
}
Here you go, a solution without "visible" loop:
generate(80,10);
function generate($start, $level){
$i=1; // Just a var
$array = array_fill(0, $level, $start); // create an array with $level elements, with value $start
array_map(function($v)use(&$i){ // Loop through the array and use $i
echo "Level $i: ".(array_product(array($v, pow(1.5, $i++))))."<br>"; // Some basic math and output
}, $array);
}
Online demo
Note that you'll need PHP 5.3+ since this function is using an anonymous function
Or, if you need just to output $start:
function generate($start, $limit)
{
$start = $start * 1.5;
echo $start."<br>";
if($limit>1)
return(generate($start,$limit-1));
}
generate(80,10);
My question - how to properly echo $level, without third parameter (0, in this case which should be incremented, no decremented:))? :)
EDIT: I would like to know better solution which will do the same, with two args:
function generate2($start, $limit,$base)
{
$start = $start * 1.5;
echo "level ".$base.": ".$start."<br>";
if($base<$limit)
return(generate2($start,$limit,$base+1));
}
generate2(80,10,1);
And final edit:
function generate($start, $limit,$i=0)
{
$i++;
$start = $start * 1.5;
echo "level ".$i.": ".$start."<br>";
if($limit>1)
{
return(generate($start,$limit-1,$i));
}
}
generate(80,10);
as answer to my self. :) Please test it (before down votes:)), and let me know about issues... Oh, i see - OP wants just 1 result, LOL...
Question wasn't clear to me (and not just to me, it seems) :)