---
# System prepended metadata

title: Bài 9

---

# Bài 9

```cpp=
#include <iostream>
#include <fstream>
using namespace std;

/*      col
    row
    0|                   1                   // 0 * 2 + 1 = 1 | 0 * 0 + 1 = 1
    1|               2   3   4               // 1 * 2 + 1 = 3 | 1 * 1 + 1 = 2
    2|           9   8   7   6   5           // 2 * 2 + 1 = 5 | 2 * 2 + 1 = 5
    3|       10  11  12  13  14  15  16      // 3 * 2 + 1 = 7 | 3 * 3 + 1 = 10
    4|   25  24  23  22  21  20  19  18  17  // 4 * 2 + 1 = 9 | 4 * 4 + 1 = 17

    với x = 11
    -> 11 < 17 => i = 3

    với x = 10
    -> 10 < 17 => i = 3

    với x = 1
    -> 1 < 2 => i = 0

    0   1   2   3   4   5   6   7   8
    25  24  23  22  21  20  19  18  17
    17  18  19  20  21  22  23  24  25

    0 - 8
    1 - 7
    2 - 6
    3 - 5
    4 - 4
*/

// Truong hop 1: Nhap so xac dinh vi tri
int *findIndex(int x)
{
    int row = 0, col = 0;

    for (int i = 0, l = x * x; i < l; i++)
    {
        if (x < (i * i + 1))
        {
            row = i - 1;
            break;
        }
    }

    for (int i = 0, l = row * 2 + 1; i < l; i++)
    {
        if (row * row + 1 + i == x)
        {
            col = i;
        }
    }

    if (row & 1) // dong le dem tu trai qua
    {
        col++;
    }
    else // dong chan dem tu phai qua
    {
        col = row * 2 - col + 1;
    }
    row++;
    static int arr[] = {row, col};
    return arr;
}

// Truong hop 2: Nhap vi tri xac dinh so
int findNumber(int row, int col)
{
    int x(0);
    row--;
    col--;

    if (!(row & 1)) // dong chan dem tu phai qua
    {
        col = row * row - col;
    }

    for (int i = 0, l = row * 2 + 1; i < l; i++)
    {
        if (i == col)
        {
            x = row * row + 1 + i;
            break;
        }
    }
    return x;
}

int main()
{
    int *arr;
    int row(0), col(0), x(0);
    int data[3];

    // doc file
    fstream file;
    file.open("b9_inp.txt", ios::in);
    if (file.is_open())
    {
        int i = 0;
        while (!file.eof())
        {
            file >> data[i];
            i++;
        }
    }
    file.close();

    // ghi file
    file.open("b9_out.txt", ios::out);
    x = data[0];
    arr = findIndex(x);
    for (int i = 0; i < 2; i++)
    {
        file << arr[i] << " ";
    }
    file << "\n";

    row = data[1];
    col = data[2];
    x = findNumber(row, col);
    file << x;
    file.close();

    return 0;
}

```