PHP Program to Factorial (Loop) with Explanation
PHP
Easy
PHP Control Flow
29 views
1 min read
81 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around factorial, loop, one. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Given n, print n! using a loop.
Input Format
One integer n.
Output Format
One integer factorial.
Constraints
0
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$n=intval($inputText);
$ans=1;
for($i=2;$i<=$n;$i++) $ans*=$i;
echo $ans;
?>
Common Mistakes
- Starting the loop from 0 (factorial becomes 0).
- Not initializing the factorial value as 1.
- Using int for large n causing overflow.
- Printing extra spaces/newlines that break format.
Solution Guide
Problem
Given n, print n! using a loop.
Input / Output
Output
One integer factorial.
Details
Common Mistakes
- Starting the loop from 0 (factorial becomes 0).
- Not initializing the factorial value as 1.
- Using int for large n causing overflow.
- Printing extra spaces/newlines that break format.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$n=intval($inputText);
$ans=1;
for($i=2;$i<=$n;$i++) $ans*=$i;
echo $ans;
?>
Solutions (0)
No solutions submitted yet. Be the first!