I am trying to learn PHP and compute the factorial of a number when given a input from a user, but I seem to be stumped. My first and last condition checkout but when I put a number bigger than 2 my result is always false, here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
</head>
<body>
<form action="" method="GET">
Enter Number: <input type="text" name="num"><br>
<input type="submit" name ="submit">
</form>
Factorial Of Your Number:
<?php
function factorial($n){
if (ctype_digit($n))
{
if ($n <= 1)
{
echo "1";
}
else
{
echo $n * factorial($n - 1);
}
}
else
{
echo "false";
}
}
if(isset($_GET['submit']))
{
$s = $_GET["num"];
factorial($s);
}
?>
</body>
</html>
I have tried editing many variations of this line echo $n * factorial($n - 1); but all result in false or an error and I can't seem to crack this. Any ideas? Note that I am trying to keep the php in the internal body not an externalphp file.
For your recursive function to work, it needs to return a number. Otherwise your function will try to calculate $n * null which throws an error.
function factorial($n){
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
if (isset($_GET['submit'])) {
$n = intval($_GET["num"]);
echo factorial($n);
}
see this solution, find factorial of a given number in PHP?
<?php
function findFactorial($num){
$fact = 1;
for($i=1; $i<$num+1; $i++){
$fact = $fact*$i;
}
return $fact;
}
$num = 5;
print_r(findFactorial($num));
?>
Here you go:
<?php
$num = $_POST["num"];
$factorial_value = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial_value = $factorial_value * $x;
}
echo "Factorial of $num is $factorial";
?>
<form method="post">
Enter a num:
<input type="text" name="num">
<input type="submit" Value="CALCULATE YOUR FACTORIAL">
</form>
Related
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 4 years ago.
I have tried to create a code which is
<html>
<body>
<form method = "post">
<?php
Number : <input type = "text" name = "prime">;
<input type = "submit" value ="Submit">;
$num = $_REQUEST["prime"];
$flag = 0;
for($i = 2; $i <= $num/2; $i++)
{
if( $num % $i == 0)
{
$flag = 1;
break;
}
}
if($flag == 0)
echo "$num is a prime number";
else
echo "$num is not a prime number";
?>
</form>
</body>
</html>
Whenever i try to run it, i get the error
Parse error: syntax error, unexpected '<', expecting end of file in
C:\xampp\htdocs\pc.php on line 5
Any help would be appreciated
Your code is wrong. There is no statement in line 5. Corrected code:
<html>
<body>
<?php
if($_SERVER['REQUEST_METHOD']=='post'){
$num = $_POST["prime"];
$flag = 0;
for($i = 2; $i <= $num/2; $i++)
{
if( $num % $i == 0)
{
$flag = 1;
break;
}
}
if($flag == 0)
echo $num." is a prime number";
else
echo $num." is not a prime number";
}
?>
<form method = "post" action="#">
Number : <input type = "text" name = "prime">
<input type = "submit" value ="Submit">
</form>
</body>
</html>
This will check current request method. If is is pot
You can follow the below procedure for solving your problem
<html>
<body>
<?php
if(isset($_POST['prime']))
{
$num = $_POST["prime"];
$flag = 0;
for($i = 2; $i <= $num/2; $i++)
{
if( $num % $i == 0)
{
$flag = 1;
break;
}
}
if($flag == 0)
echo "$num is a prime number";
else
echo "$num is not a prime number";
}
?>
<form method = "post">
<input type = "text" name="prime">
<input type = "submit" value ="Submit">
</form>
</body>
</html>
I'm having some issues getting the input code to work with the equation. I've been trying for a while (I'm new to coding) and searching, while not being able to make it work in any way. This is what I ended up with. Can anyone help me? Thanks in advance.
<!DOCTYPE HTML>
<html>
<body>
<form action="" method="post">
<br />Choose a number to be the nth in the Fibonacci sequence: <input type="number" name="fibnum">
<input type="submit">
</form> <br /> <br />
<?php
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
echo "There are no Fibonacci numbers of negative values.";
}
elseif ($fibnum == 0){
echo "0";
}
elseif ($fibnum == 1){
echo "1";
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
echo $sum;
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
</body>
</html>
to make it work all you need to do is change the echo's to returns like so:
<?php
$_POST['fibnum']=11;
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
return ( "There are no Fibonacci numbers of negative values.");
}
elseif ($fibnum == 0){
return ("0");
}
elseif ($fibnum == 1){
return ("1");
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
return ($sum);
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
working demo: http://ideone.com/e0xeY7
you were pushing integers into echo. in a recursive formula, returning the value goes back to the calling entity, not automatically outside the function.
Take a look at this:
<!DOCTYPE HTML>
<html>
<body>
<form action="" method="post">
<br />Choose a number to be the nth in the Fibonacci sequence: <input type="number" name="fibnum">
<input type="submit">
</form> <br /> <br />
<?php
if(isset($_POST['fibnum'])){
$fibnum = $_POST['fibnum'];
function fibRec($fibnum){
if ($fibnum < 0){
echo "There are no Fibonacci numbers of negative values.";
}
elseif ($fibnum == 0){
return 0;
}
elseif ($fibnum == 1){
return 1;
}
else {
$sum = fibRec($fibnum-1)+fibRec($fibnum-2);
return $sum;
}
}
$fib = fibRec($fibnum);
echo $fib;
}
?>
</body>
</html>
You can also use PHI constant associated with golden ratio to calculate nth fibonacci number. it is considered that fibonnaci number until 5th iteration are not as per golden ratio so you can have it like below :
<?php
$fibnum = intval($_POST['fibnum']);
const PHI = 1.6180339887;
$f = [0, 1, 1, 2, 3];
echo getNthFibo($fibnum);
function getNthFibo($i)
{
if($i < 5){
return $f[$i];
}
// Starting from 5th iteration of fibo function
$n = 5;
$fn = 3;
while ($n < $i) {
$fn = round($fn * PHI);
$n++;
}
return $fn;
}
so the task I'm trying to complete here is comparing a user input number against the fibonacci sequence and if it is a fibonacci number the program will echo true, if not it will echo false.
Can someone tell me where I'm going wrong?
this is my first file:
<?php
function print_fibonacci($n){
$first = 0;
$second = 1;
echo "Fibonacci Series: \n";
echo $first.' '.$second.' ';
for($i=2;$i<$n;$i++){
$third = $first + $second;
echo $third.' ';
$first = $second;
$second = $third;
}
}
/* Function call to print Fibonacci series upto 6 numbers. */
print_fibonacci(16);
?>
<form method="POST" action="fibonacci3.php"><br>
<label>Input a number to check if it is fibonacci or not.</label><br>
<input name="fib" type="text" placeholder="#" /><br>
<input type="submit" value="OK!" />
</form>
This outputs the fibonacci sequence until the 16th fibonacci number, and is followed by a form which allows a user to enter a number.
The next file is fibonacci3.php as referenced in the form.
<?php
include "fibonacci2.php";
$n = $_POST["fib"];
function fibonacci($n) {
//0, 1, 1, 2, 3, 5, 8, 13, 21
/*this is an error condition
returning -1 is arbitrary - we could
return anything we want for this
error condition:
*/
if((int)$n <0){
return -1;
echo "False";
}
if ((int)$n == 0){
return 0;
echo "0";
}
if((int)$n == 1 || $n == 2){
return 1;
}
$int1 = 1;
$int2 = 1;
$fib = 0;
for($i=1; $i<=$n-2; $i++ )
{
$fib = $int1 + $int2;
//swap the values out:
$int2 = $int1;
$int1 = $fib;
}
if ($fib = $int1 + $int2 && $n == $fib){
echo "True!";
} else {
echo "False!";
}
return $fib;
}
fibonacci((int)$n);
?>
I thought this might be correct but it's not outputting anything when the user inputs a number.
$n = 'Your number';
$dRes1 = sqrt((5*pow($n, 2))-4);
$nRes1 = (int)$dRes1;
$dDecPoint1 = $dRes1 - $nRes1;
$dRes2 = sqrt((5*pow($n, 2))+4);
$nRes2 = (int)$dRes2;
$dDecPoint2 = $dRes2 - $nRes2;
if( !$dDecPoint1 || !$dDecPoint2 )
{
echo 'True';
}
else {
echo 'False';
}
This question already has answers here:
Create a mechanism to pass in a positive integer and display all the values of the Fibonacci series up to and including the specified value
(2 answers)
Closed 8 years ago.
How would I create a mechanism to pass in a positive integer and display the operand, the Fibonacci series number of the operand and the sum of all the values of the Fibonacci series up to and including the specified value?
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="main.css"/>
<title>Fib Activity 3</title>
</head>
<body>
<h1>Pick Category Using GET</h1>
Films
Music
Books
<br />
<h2>Fibonacci</h2>
<form method="get" action="fib3.php">
<fieldset>
<label for="powerof">Fibonacci: </label>
<input type="text" name="powerof" value="<?php echo $_GET['powerof']; ?>"/>
<input type="submit" name='Go' value="Calculate" />
</fieldset>
</form>
<?php
$message = 'The fibonacci sequence is: <br />1<br />2<br />';
$powerof = 0;
$max = 10;
$temp = $max;
if (isset($_GET['powerof'])) {
$powerof = $_GET['powerof'];
}
if ($powerof > 100) {
$powerof = 100;
$message = 'Sorry, your input was too high. I converted it to the maximum value of 100.<br />The fibonacci sequence is: <br />1<br />2<br />';
}
$x = 0;
$y = 1;
$z = 0;
$counter = 0;
while ($counter < $powerof) {
if ($counter <= 1) {
$z = 1;
} else {
$z = $x + $y;
}
echo ($z. "<br />");
$x = $y;
$y = $z;
$counter++;
}
?>
</body>
</html>
all help is appreciated
First off, you aren't quite getting the Fibonacci series correct. The first number in the Fibonacci series is 0. The script I wrote here assumes that $powerof needs to be at least 1 (this can be easily changed if you need).
I also wrote this using a recursive function which takes the number you are going to. the first number, and the second number. It will loop through by calling itself and each time, it will print out the fibonacci series at the number.
<?php
$powerof = 0;
if (isset($_GET['powerof'])) {
$powerof = $_GET['powerof'];
}
$message = 'The fibonacci sequence is:';
if ($powerof > 100) {
$powerof = 100;
$message = 'Sorry, your input was too high. I converted it to the maximum value of 100.<br />The fibonacci sequence is:';
}
echo $message;
$first = 0;
$second = 1;
if ($powerof > 1) {
echo '<br>0<br>1';
} else if ($powerof < 1) {
echo ' Invalid input';
} else {
fib($powerof, $first, $second);
}
function fib($powerof, $first, $second) {
if( $powerof > 0 ) {
$sum = $first + $second;
$first = $second;
$second = $sum;
echo $sum.'<br>';
fib($n-1, $first, $second);
}
}
?>
I hope this all makes sense, if you have any more questions, let me know
Hi, i am having trouble in understanding how session works. I am trying to write a program that will repeatedly request a number to be entered and each time the number is entered the program is to print out:
that number
the sum of all the numbers entered
the count in how many times I submitted
This is my code so far:
<?php
session_start();
if(isset($_session['count']))
{
$_session['count'] = $count;
}else{
$_session['count'] = 0;
}
?>
<html>
<head>
<title>number</Title>
<style>
</style>
<body>
<form action = "numbers.php" method = "post">
Numbers: <input type "text" name = "number" size = "6"/>
<input type = "submit" value = "submit" name = "submit"/>
<p>
</form>
</body>
</head>
</Html>
<?php
if(isset($_POST["submit"]))
{
$number = $_POST['number'];
If (is_numeric($number))
{
$count = $_session['count'] + $number;
print "Last number entered: ".$number;
print "<br>Total internal numbers: ".$count;
}
}
?>
Im trying to store my $count variable so each time i submit it outputs the total sum of the numbers entered
You set $_session['count'] = $count; before you have a variable called $count. You have to update the session value after you've set $count like:
$count = $_session['count'] + $number;
$_session['count'] = $count;
You can then replace the top of your script with:
if(!isset($_session['count']))
{
$_session['count'] = 0;
}
On the start you are using undefined variable $count. Edit it to:
if(!isset($_session['count']))
$_session['count'] = 0;
Then add a new line:
If (is_numeric($number))
{
$count = $_SESSION['count'] + $number;
$_SESSION['count'] = $count;
print "Last number entered: ".$number;
print "<br>Total internal numbers: ".$count;
}
OR second part edit to:
If (is_numeric($number))
{
$_SESSION['count'] += $number;
print "Last number entered: ".$number;
print "<br>Total internal numbers: ".$_SESSION['count'];
}
<?php
if(isset($_POST["submit"]))
{
$number = $_POST['number'];
If (is_numeric($number))
{
$count = $_session['count'] + $number;
$_session['count'] = $count;
print "Last number entered: ".$number;
print "<br>Total internal numbers: ".$count;
}
}
?>
Here's the working example. [TESTED]
You have to assign $_SESSION['count']=$count;
<?php
session_start();
//Code commented as not required.
/*if(isset($_session['count']))
{
$_session['count'] = $count;
}else{
$_session['count'] = 0;
}
*/?>
<html>
<head>
<title>number</Title>
<style>
</style>
<body>
<form action = "" method = "post">
Numbers: <input type "text" name = "number" size = "6"/>
<input type = "submit" value = "submit" name = "submit"/>
<p>
</form>
</body>
</head>
</Html>
<?php
if(isset($_POST["submit"]))
{
$number = $_POST['number'];
if (is_numeric($number))
{
$count = $_SESSION['count'] + $number;
$_SESSION['count']=$count;
print "Last number entered: ".$number;
print "<br>Total internal numbers: ".$count;
}
}
?>