Формула трикутника Паскаля з прикладами

⚡ Розумний підсумок

Pascal's Triangle is a triangular arrangement of numbers where each value equals the sum of the two numbers directly above it, revealing deep patterns in combinatorics, binomial expansions, and probability that have fascinated mathematicians for centuries.

  • 🔺 Структура: Кожен рядок починається та закінчується на 1, а внутрішні значення утворюються шляхом додавання двох чисел вище.
  • 📐 Біноміальний зв'язок: Рядок n стовпець k дорівнює біноміальному коефіцієнту C(n, k), що робить трикутник візуальним пошуком комбінацій.
  • 🔢 Приховані закономірності: Суми рядків дорівнюють степеням числа 2, а діагональні суми генерують послідовність Фібоначчі.
  • ✅ Три методи: Ви можете побудувати його за попередніми рядками, обчислюючи біноміальні коефіцієнти або за допомогою ітеративного скороченого методу зі зміненими коефіцієнтами.
  • 🧪 Область застосування: Використовується в алгебрі, теорії ймовірностей, інформатиці та комбінаторних доказах у сучасних навчальних програмах.

Що таке трикутник Паскаля?

Pascal's Triangle is a triangular array of numbers that follows a simple pattern based on the row above it. It was popularized by French mathematician Blaise Pascal in the 17th century. The triangle begins with a single "1" at the top, and every subsequent row starts and ends with "1" as well.

Трикутник Паскаля

Beyond its elegant shape, Pascal's Triangle encodes deep mathematical relationships. It is closely tied to the binomial theorem, combinatorial counting, and probability, which is why it appears in algebra, statistics, and computer science classrooms worldwide.

Історія трикутника Паскаля

Although named after Blaise Pascal, the triangle predates him by centuries. The Chinese mathematical text "The Nine Chapters on the Mathematical Art" contains one of the earliest known examples, displaying many of the same patterns we use today.

Перський математик Аль-Караджі та індійський вчений Pingala also explored similar arrays. Pascal formalized the triangle's properties in his 1654 treatise "Traité du triangle arithmétique," which gave the structure its modern name in Western mathematics.

Побудова трикутника Паскаля

Constructing Pascal's Triangle is straightforward. The only rule to remember is that each row starts and ends with 1, and every other number is built from the row above.

Для будь-якого рядка r та стовпця c значення дорівнює сумі чисел у стовпцях c-1 та c рядка r-1.

Тут,

  • r = 3, 4, 5, ...
  • n and c = 2, 3, 4, ..., r-1.

Here are the steps to build Pascal's Triangle:

Крок 1) Почніть із заповнення перших двох рядків.

Побудова трикутника Паскаля

Крок 2) Другий елемент третього рядка – це сума першого та другого чисел у другому рядку.

Побудова трикутника Паскаля

Крок 3) The fourth row begins with "1". The second number is 3, which is the sum of 1 and 2 (highlighted in blue).

На зображенні нижче показано, як заповнити четвертий ряд:

Побудова трикутника Паскаля

Крок 4) П'ятий рядок складається з п'яти чисел. Ми вже знаємо шаблон заповнення рядків з попередніх кроків.

Побудова трикутника Паскаля

Формула трикутника Паскаля – біноміальний коефіцієнт

A binomial coefficient counts the number of ways to choose a subset of k elements from a collection of n elements. It is commonly written as "C(n, k)" or "n choose k."

Біноміальний коефіцієнт визначається як:

Формула трикутника Паскаля – біноміальний коефіцієнт

The "!" symbol denotes the factorial of a number.

n! = n.(n-1).(n-2)...3.2.1

Наприклад,

5! = 5.4.3.2.1

= 120

So, C(5, 3) or "5 choose 3" = 5! / 3!(5-3)!

= 120/12

= 10

Спосіб 1: Побудова трикутника Паскаля за попереднім рядком

The procedure here mirrors how we drew the triangle manually. Suppose we want to generate Pascal's triangle up to seven rows.

Для цього потрібно виконати такі дії:

Крок 1) Start the topmost row with "1".

Крок 2) For row "r", element "c" will be the sum of column "c-1" and column "c" of row "r-1".

Крок 3) The first and last numbers in every row will always be "1".

Дотримання цих трьох простих кроків дозволяє нам систематично побудувати весь трикутник.

C++ Code трикутника Паскаля за попереднім рядком

#include <bits/stdc++.h>
using namespace std;
void printRow(int n)
{
  int numbers[n][n];
  for (int row = 0; row < n; row++)
  {
    for (int col = 0; col <= row; col++)
    {
      if (col == 0 || col == row)
      {
        numbers[row][col] = 1;
      }
      else
      {
        numbers[row][col] = numbers[row - 1][col - 1] + numbers[row - 1][col];
      }
      cout << numbers[row][col] << "\t";
    }
    cout << endl;
  }
}
int main()
{
  int n;
  cout << "How many rows: ";
  cin >> n;
  printRow(n);
}

вихід:

How many rows: 7
1
1       1
1       2       1
1       3       3       1
1       4       6       4       1
1       5       10      10      5       1
1       6       15      20      15      6       1

Python Code Формула трикутника Паскаля за попереднім рядком

def printRow(n):
    numbers = [[0 for row in range(n)]
               for col in range(n)
               ]
    for row in range(len(numbers)):
        for col in range(0, row+1):
            if row == col or col == 0:
                numbers[row][col] = 1
            else:
                numbers[row][col] = numbers[row-1][col-1]+numbers[row-1][col]

            print(numbers[row][col],end="\t")
        print("\n")
n = int(input("How many rows: "))
printRow(n)

Pascal's Triangle Example Output:

How many rows: 7
1
1       1
1       2       1
1       3       3       1
1       4       6       4       1
1       5       10      10      5       1
1       6       15      20      15      6       1

Аналіз складності

A двовимірний масив is used in this implementation. Given that N is the number of rows in Pascal's triangle, this requires N2 одиничних просторів. Отже, складність простору дорівнює O(N2).

The function uses two nested loops, each running up to "N" times. So, the time complexity is also O (N2), або квадрат часової складності.

Спосіб 2: Побудова трикутника Паскаля шляхом обчислення біноміального коефіцієнта

We can derive the numbers of Pascal's triangle directly using binomial coefficients. The diagram below illustrates the relationship:

Побудова трикутника Паскаля шляхом обчислення біноміального коефіцієнта

Here are the steps to build Pascal's Triangle by calculating the binomial coefficient:

Крок 1) Найвищий рядок — це C(0, 0). Використовуючи наведену вище формулу, C(0, 0) = 1, оскільки 0! = 1.

Крок 2) For row "i", there will be a total of "i" elements. Each item is calculated as C(n, r), where n is i-1.

Крок 3) Repeat step 2 for as many rows of Pascal's triangle as you want to generate.

C++ Code Трикутник Паскаля за допомогою біноміального коефіцієнта

#include <iostream>
using namespace std;
int factorial(int n)
{
    int result = 1;
    for (int i = 1; i <= n; i++)
    {
        result *= i;
    }
    return result;
}
int binomialCoefficient(int n, int r)
{
    int result = 1;
    if (r > n)
    {
        return -1;
    }
    result = factorial(n) / (factorial(r) * factorial(n - r));
    return result;
}
void printPascalTriangle(int row)
{
    for (int i = 0; i <= row; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            cout << binomialCoefficient(i, j) << "\t";
        }
        cout << endl;
    }
}
int main()
{
    int n;
    cout << "Enter row number: ";
    cin >> n;
    printPascalTriangle(n);
}

вихід:

Enter row number: 9
1
1	1
1	2	1
1	3	3	1
1	4	6	4	1
1	5	10	10	5	1
1	6	15	20	15	6	1
1	7	21	35	35	21	7	1
1	8	28	56	70	56	28	8	1
1	9	36	84	126	126	84	36	9	1

Python Code Трикутник Паскаля за допомогою біноміального коефіцієнта

def factorial(n):
    result = 1
    for i in range(1,n+1):
        result*=i
    return result
def binomialCoefficient(n,r):
    result =1
    if r>n:
        return None
    result = factorial(n) / (factorial(r) * factorial(n - r))
    return int(result)
def printPascalTriangle(row):
    for i in range(row+1):
        for j in range(i+1):
            print(binomialCoefficient(i, j), end="\t")
        print()
# print(binomialCoefficient(3, 2))
n = int(input("Enter row number: "))
printPascalTriangle(n)

Pascal's Triangle Example Output:

Enter row number: 8
1
1       1
1       2       1
1       3       3       1
1       4       6       4       1
1       5       10      10      5       1
1       6       15      20      15      6       1
1       7       21      35      35      21      7       1
1       8       28      56      70      56      28      8       1

Аналіз складності

Three loops are used in this implementation: one to compute the binomial coefficient and two more to iterate through every row and column. With respect to the number of rows, all three loops run up to "n" times. Consequently, the overall time complexity is O(n3).

Просторова складність є постійною, оскільки ми не зберігаємо жодних проміжних результатів. Програма обчислює кожен елемент на льоту та виводить його в рядку, тому просторова складність зменшується до O (1).

Спосіб 3: Побудова трикутника Паскаля за модифікованим біноміальним коефіцієнтом

У попередньому методі ми використовували формулу біноміального коефіцієнта для обчислення кожного елемента. Модифікований підхід виводить C(n, r) безпосередньо з C(n, r-1), зменшуючи роботу на один порядок.

Here are the steps to build Pascal's Triangle by the modified binomial coefficient:

Крок 1) Initiate the first row with "1".

Крок 2) Calculate C(n, r), where "n" is the row number and "r" is the column index. Assign that value to a variable C.

Крок 3) For computing the next coefficient, use C * (n - k) / k. Assign this new value back to C.

Крок 4) Continue step 3 until "k" reaches the end of the row. After each iteration, increment k by one.

C++ Code для трикутника Паскаля за допомогою модифікованого біноміального коефіцієнта

#include <bits/stdc++.h>
using namespace std;
void printpascalTriangle(int n)
{
  for (int row = 1; row <= n; row++)
  {
    int previous_coef = 1;
    for (int col = 1; col <= row; col++)
    {
      cout << previous_coef << "\t";
      previous_coef = previous_coef * (row - col) / col;
    }
    cout << endl;
  }
}

int main()
{
  int n;
  cout << "How many rows: ";
  cin >> n;
  printpascalTriangle(n);
}

вихід:

How many rows: 5
1
1       1
1       2       1
1       3       3       1
1       4       6       4       1

Python Code для трикутника Паскаля за допомогою модифікованого біноміального коефіцієнта

def printpascalTriangle(n):
    for row in range(1, n+1):
        previous_coef = 1
        for col in range(1, row+1):
            print(previous_coef, end="\t")
            previous_coef = int(previous_coef*(row-col)/col)
        print()
n = int(input("How many rows: "))
printpascalTriangle(n)

Pascal's Triangle Patterns Output:

How many rows: 5
1
1       1
1       2       1
1       3       3       1
1       4       6       4       1

Аналіз складності

The implementation uses two loops, each running a maximum of "n" times, where "n" is the number of rows in the triangle. So, the time complexity is О (н.)2), у квадраті часу.

Щодо просторової складності, нам не потрібен масив для зберігання. Ми використовуємо лише одну змінну для збереження попереднього біноміального коефіцієнта, тому нам потрібен лише один додатковий пробіл. Таким чином, просторова складність дорівнює O (1).

Застосування трикутника Паскаля

Here are some practical applications of Pascal's Triangle:

Біноміальні розширення: The coefficients of any binomial expansion can be read directly from Pascal's triangle. Here is an example:

(х + у)0 1
(х + у)1 1.x + 1.y
(х + у)2 1x2 + 2xy + 1y2
(х + у)3 1x3 + 3x2та + 3xy2 + 1y3
(х + у)4 1x4 + 4x3та + 6x2y2 + 4xy3 + 1y4

Розрахунок комбінацій: The elements of Pascal's triangle correspond directly to binomial coefficients. For example, if you have 6 balls and want to choose 3, the answer is 6C3. You can find that value in the 3rd element of the 6th row of Pascal's triangle.

Імовірність: Pascal's Triangle is widely used to compute probabilities in coin tosses, dice problems, and other combinatorial events where each outcome corresponds to a binomial distribution.

Цікаві факти про трикутник Паскаля

Here are some facts you will find interesting about Pascal's triangle:

  • Сума всіх елементів у будь-якому рядку завжди є степенем числа 2.

Факти про трикутник Паскаля

  • Діагональні суми рядків генерують послідовність Фібоначчі.

Факти про трикутник Паскаля

  • Кожен рядок відповідає коефіцієнтам у розкладі (a+b)n.
  • Якщо заштрихувати лише непарні числа, отримана фігура утворює фрактал трикутника Серпінського.

Поширені запитання

Хоча названий на честь Блеза Паскаля, який формалізував його в 1654 році, трикутник був відомий у Китаї, Індії та Персії століттями раніше. Математики, такі як Цзя Сянь, Ян Хуей, Pingала, і Аль-Караджі вивчав подібні масиви задовго до Паскаля.

Кожен елемент у трикутнику Паскаля дорівнює біноміальному коефіцієнту C(n, k). Числа в рядку n дають коефіцієнти (a + b), піднесені до степеня n, що робить трикутник таблицею швидкого пошуку для біноміальних розкладів.

Сума всіх чисел у n-му рядку трикутника Паскаля дорівнює 2, піднесеним до степеня n. Наприклад, рядок 4 містить 1, 4, 6, 4, 1, що в сумі дає 16, рівно 2 у 4-му степені.

Якщо додати числа вздовж неглибоких діагоналей трикутника Паскаля, отримані суми утворюють послідовність Фібоначчі: 1, 1, 2, 3, 5, 8, 13 тощо. Це один із найелегантніших прихованих візерунків трикутника.

Трикутник Паскаля моделює ймовірності подій з двома рівноймовірними результатами, такими як підкидання монети. Рядок n показує, скількома способами можна отримати k орлів за n підкидань, що безпосередньо впливає на біноміальний розподіл ймовірностей.

Системи штучного інтелекту використовують біноміальні коефіцієнти, взяті з трикутника Паскаля, для вибору ознак, вибірки та комбінаторної оптимізації. Агенти навчання з підкріпленням та розв'язувачі символьної математики також використовують трикутник, коли міркують про розклади поліноміів та задачі дискретного вибору.

Так. Репетитори з математики на базі штучного інтелекту створюють візуалізації по рядках, адаптивні практичні задачі та миттєві зворотні зв'язки щодо вправ на біноміальні коефіцієнти. Вони допомагають учням пов'язувати трикутник з комбінаціями, ймовірністю та теоремою бінома у власному темпі.

Підсумуйте цей пост за допомогою: