Factorial function in C

I recently started reading Hack: The Art of Exploitation by John Erickson. In the book, it has the following function, which I will call (A):

int factorial (int x)       // .......... 1
{                           // .......... 2
    int i;                  // .......... 3
    for (i = 1; i < x; i++) // .......... 4
        x *= i;             // .......... 5
    return x;               // .......... 6
}                           // .......... 7

This particular function is on pg. 17. Prior to this function, I understood everything that he described. In fairness, he explained in detail all the elements in (A), with the exception of the concept of return. However, I just don’t see how (A) the process should be described.

x! = x * (x-1) * (x-2) * (x-3)

etc., which I will call (B). If someone can take the time to figure this out in detail, I would really appreciate it. Since I ask you for help, I will consider the elements that I believe I understand in order to potentially expose the elements that I think I understand, but actually not, but also help you help me take a step from of how (A) is supposed to be a representation of (B).

Well, that’s what I think I understand.

  • On line 1, c (int x), xan integer type is assigned. What I'm less sure about is that in factorial (int x), int is xassigned the type factorial, or even if factorial is a type.

  • Line 3 is simple; iassigned an integer value of the type.

  • 4 , , . , 4 . i, 1. , 4, i < x, , , i , x, . i++ , / "while a, then b" 1 i.

  • 5 , x *= i i * x, , , , 4 5.

" . , , .

+4
4
  • 1 N-1. (, "N" )
  • x = N.
  • x = N * 1.
  • 2 x = N * 1 * 2.
  • N-1 x = N * 1 * 2 *.... (N-1).
  • N .

, N! .

+1

, . , :

int factorial (int x)       // .......... 1
{                           // .......... 2
    int i;                  // .......... 3
    for (i = 1; i < x; i++) // .......... 4
        x *= i;             // .......... 5
    return x;               // .......... 6
}                           // .......... 7

1:

, int factorial (...) - , , factorial, int. int x - , , x int. , , .

3:

, int. , , , .

4:

, i, 3, . i=1 , 1. i<x , , x. i++ , , , .

5:

x*=1 , x i. , . , , x 5, i, 1, 2, 3 4 ( 1 , x), x 1, 2, 3 4. , x 5 * 1 * 2 * 3 * 4, 5.

6:

x , , return - ​​ x ( 5 , ).

:

int f;
f = factorial(5);

x 5 f (, - 5 * 1 * 2 * 3 * 4)

+2

, , , . , for-loop , x , i. x , .

+2

: x * = i;

: x = x * i;

, < . , x - 1;

, 1, : x * 1 * 2 * 3 *... * (x - 1)

You can change this to get: 1 * 2 * 3 * ... * (x - 1) * x

+1
source

Source: https://habr.com/ru/post/1535848/


All Articles