Robson » Little Red Book » Factorial

Chapter 3 - Question 1

Using a small input integer, N say, compute and print factorial N.

Solution 1

C++:

#include <stdio.h>
#include <stdlib.h>
 
using namespace std;
 
int main(int argc, char **argv)
{
   int n = atoi(argv[1]);
   int total = 1;
   
   for (int a = 1; a <= n; a++)
       total *= a;
       
   printf("The factorial of %d is %d.", n, total);    
}

Example use:

C:\code>factorial 4
The factorial of 4 is 24.
C:\code>

Solution 2

VB:

Sub main()
 
   ' this holds the factorial
   Dim lngTotal As Long
   ' this will be the number entered by the user
   Dim n As Integer
   
   ' ensure random numbers are random
   Randomize
   
   ' get something from the user and convert it into an integer
   n = Val(InputBox("Enter a small integer", "Factorial", Int(10 * Rnd) + 1))
   
   ' check they entered a positive number
   If (n > 0) Then
       ' start at 1
       lngTotal = 1
       ' loop up to the user entered number
       For a = 1 To n
           ' multiply by each number
           lngTotal = lngTotal * a
       Next
       ' show the original number and its factorial
       MsgBox "The factorial of " & n & " is " & lngTotal & ".", vbInformation, "Factorial"
   End If
 
End Sub

The colours are set up for PHP/C++ so they will look a bit strange.

Solution 3

PHP:

<?
   // generate a random integer
   $n = intval(mt_rand(1, 10));
   // start the total at one
   $total = 1;
   
   // loop from 1 to the specified number
   for ($a = 1; $a <= $n; $a++)
       // multiply the total by this amount
       $total *= $a;
       
   // show the original number and the factorial    
   echo 'The factorial of ' . $n . ' is ' . $total;
?>

Which produces:

The factorial of 2 is 2

Solution 4

Javascript:

<script language="javascript">
<!--
   var n = prompt("Enter a small integer", 5);
   var total = 1;
   for (var a = 1; a <= n; a++)
       total = total * a;
   alert("The factorial of " + n + " is " + total + ".");
-->
</script>

Log

© 2004-17 robson | cc unless stated