> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/ko/in-depth-articles/31-latex-is-more-powerful-than-you-think-computing-the-fibonacci-numbers-and-turing-completeness.md).

# LaTeX는 당신이 생각하는 것보다 더 강력하다 - 피보나치 수 계산과 튜링 완전성

**저자: Robert Murrish (2012년 4월 (2023년 4월 Overleaf 편집))**

LaTeX는 강력한 도구입니다. 사실 너무 강력해서 문서 마크업 이상의 용도로도 사용할 수 있습니다. LaTeX는 [튜링 완전](https://en.wikipedia.org/wiki/Turing_completeness); 즉, 거의 무엇이든 계산하도록 프로그래밍할 수 있습니다.

LaTeX의 범용 프로그래밍 능력을 보여 주기 위해, 여기서는 첫 번째 피보나치 수를 계산하는 예제를 살펴보겠습니다. 이것이 튜링 완전성의 증명은 아니지만, LaTeX로 구현한 완전한 알고리즘의 좋은 예입니다.

### 피보나치 수열

피보나치 수열의 각 수는 앞의 두 항의 합이며, 시작점을 제공하기 위해 처음 두 항은 1로 정의됩니다.

이 수들을 계산하는 새 명령을 작성할 수 있습니다. 아직 만들지 않은 명령을 어떻게 호출할지부터 정해 봅시다:

```latex
\fibonacci{10}
```

이 명령이 LaTeX 문서에서 호출되면 다음 값들의 목록을 출력해야 합니다. `n` 피보나치 수(여기서 `n=10` 은 여기 예제 호출에서의 값입니다). 다음은 `\fibonacci` 명령(즉, LaTeX 매크로)의 코드입니다. 어떻게 동작하는지 살펴봅시다.

```latex
\documentclass{article}
\begin{document}

\newcount\temp
\newcount\fone
\newcount\ftwo
\newcount\fcnt

\newcommand{\fibonacci}[1]{%
	\fcnt=#1
	\fone=1
	\ftwo=1
	\temp=0
	\the\fone, \the\ftwo
	\let\next=\fibloop
	\fibloop
}

\def\fibloop{, %
	\temp=\fone
	\fone=\ftwo
	\advance\ftwo by \temp
	\ifnum\fcnt=0
            \let\next=\relax
        \else
            \advance\fcnt by -1
        \fi
	\the\ftwo
	\next
}

(\fibonacci{10})
\end{document}
```

[이 예제를 Overleaf에서 열기](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Fibonacci+sequence+in+LaTeX\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Cnewcount%5Ctemp%0A%5Cnewcount%5Cfone%0A%5Cnewcount%5Cftwo%0A%5Cnewcount%5Cfcnt%0A%0A%5Cnewcommand%7B%5Cfibonacci%7D%5B1%5D%7B%25%0A%09%5Cfcnt%3D%231%0A%09%5Cfone%3D1%0A%09%5Cftwo%3D1%0A%09%5Ctemp%3D0%0A%09%5Cthe%5Cfone%2C+%5Cthe%5Cftwo%0A%09%5Clet%5Cnext%3D%5Cfibloop%0A%09%5Cfibloop%0A%7D%0A%0A%5Cdef%5Cfibloop%7B%2C+%25%0A%09%5Ctemp%3D%5Cfone%0A%09%5Cfone%3D%5Cftwo%0A%09%5Cadvance%5Cftwo+by+%5Ctemp%0A%09%5Cifnum%5Cfcnt%3D0%0A++++++++++++%5Clet%5Cnext%3D%5Crelax%0A++++++++%5Celse%0A++++++++++++%5Cadvance%5Cfcnt+by+-1%0A++++++++%5Cfi%0A%09%5Cthe%5Cftwo%0A%09%5Cnext%0A%7D%0A%0A%28%5Cfibonacci%7B10%7D%29%0A%5Cend%7Bdocument%7D)

먼저, 나중에 사용할 몇 가지 변수를 설정합니다.  `\newcount` 명령은 정수를 담는 데 사용할 수 있는 변수를 만들어 줍니다. 여기서는 네 개를 만듭니다: `\fcnt`, `\fone`, `\ftwo` 및 `\temp`. 이들은 새 변수가 아니라 기존 카운터의 별칭과 비슷하다고 보는 편이 더 맞습니다. [LaTeX 카운터](/latex/ko/formatting/10-counters.md) 는 다음과 같이 직접 사용할 수 있습니다. `\count0`, `\count1`, 등으로 말입니다. 하지만 이름을 부여하면 이미 사용 중인 카운터에 값을 쓰는 일을 막을 수 있습니다. 궁금하다면 이 코드의 변수 하나를 `\count0`로 바꿔 보세요. 그러면 문서의 나머지 부분에서 페이지 번호가 잘못됩니다.

다음은 `\fibonacci` 명령입니다. 우리는 다음으로 이를 만듭니다. `\newcommand`, 여기에는 이름, 인수의 개수, 그리고 인수로 처리할 TeX 코드를 제공합니다. 이 명령에서는 피보나치 수를 몇 개 출력할지에 대한 단일 인수를 받습니다. 이 명령의 내용은 간단합니다. 변수의 초기값을 설정하고, 처음 두 피보나치 수는 계산할 필요가 없으므로 그대로 출력한 뒤, 계산의 핵심을 맡을 `\fibloop`를 호출합니다.

명령은 `\fibloop` 도 같은 방식으로 선언되지만, 이 명령의 핵심은 반복 구조입니다. 우리는 `\next`라는 명령을 사용하며, 이는 `\fibloop` 안에서 `\fibonacci`로 초기화되고 `\fibloop` 안에서 반복을 제어하는 데 사용됩니다. `\fibloop` 는 다음이 될 때까지 반복됩니다. `\next` 가 다음 내부의 코드에 의해 변경될 때까지 `\fibloop` 명령 자체에 의해 변경될 때까지입니다. 우리는 단지 `n` 번만 반복하면 되므로 `\ifnum` 라는 문을 사용합니다. 이 문은 카운터(`\fcnt`)의 값을 확인한 다음, 아직 기준값 0에 도달하지 않았다면 `\fcnt` 는 루프가 반복될 때마다 1씩 감소합니다. 조건이 충족되면 `\next` 을 `\relax`를 설정하여 `\fibloop` 가 반복되는 것을 막습니다. 마지막 `\next` 명령은 아무 일도 하지 않으며, 루프는 종료됩니다.

이 블록의 다른 명령들은 수열의 다음 피보나치 수를 계산하고, 다음 반복을 위해 변수 값들을 업데이트합니다.  `\the\ftwo` 명령은 현재 피보나치 수의 값을 문서에 출력하며, 각 값을 구분하기 위해 `\fibloop` 명령의 맨 위에 쉼표와 공백이 있는 것도 보일 것입니다.

#### 결과

이 코드를 가장 쉽게 실행해 보는 방법은 코드 표시 아래쪽의 **이 예제를 Overleaf에서 열기** 링크를 사용해 Overleaf에서 실행하는 것입니다. 피보나치 수열은 빠르게 커지므로, 이 구현에서는 `n>44` 이면 정수 오버플로가 발생합니다.

### 다음에는 무엇을 볼까요?

LaTeX가 튜링 완전하다는 비공식적인 증명으로, 다음의 코드를 제시합니다. 이것은 [NAND 게이트](https://en.wikipedia.org/wiki/NAND_gate):

```latex
\newcount\nanone
\newcount\nantwo

\newcommand{\nand}[2]{%
\nanone=#1
\nantwo=#2
  \ifnum\nanone=\nantwo
    \ifnum\nanone=0\relax 1
      \else 0
    \fi
   \else 1
\fi
}
```

NAND(그리고 NOR) 논리 게이트는 다른 어떤 논리 게이트도 이 한 종류의 게이트만으로 만들 수 있다는 흥미로운 성질을 지닙니다. 기본 논리 게이트들로 래치, 플립플롭, 메모리를 만들 수 있습니다. 이들은 범용 컴퓨터의 구성 요소입니다. Overleaf에서 열 수 있는 다음 예제로, 가능한 네 가지 입력 각각에 대해 이 NAND 게이트를 테스트해 볼 수 있습니다.

```latex
\documentclass{article}
\begin{document}

\newcount\nanone
\newcount\nantwo

\newcommand{\nand}[2]{%
\nanone=#1
\nantwo=#2
  \ifnum\nanone=\nantwo
    \ifnum\nanone=0\relax 1
      \else 0
    \fi
   \else 1
\fi
}

\nand{0}{0}
\nand{0}{1}
\nand{1}{0}
\nand{1}{1}
\end{document}
```

[이 예제를 Overleaf에서 열기](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=NAND+gate+in+LaTeX\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%0A%5Cnewcount%5Cnanone%0A%5Cnewcount%5Cnantwo%0A%0A%5Cnewcommand%7B%5Cnand%7D%5B2%5D%7B%25%0A%5Cnanone%3D%231%0A%5Cnantwo%3D%232%0A++%5Cifnum%5Cnanone%3D%5Cnantwo%0A++++%5Cifnum%5Cnanone%3D0%5Crelax+1%0A++++++%5Celse+0%0A++++%5Cfi%0A+++%5Celse+1%0A%5Cfi%0A%7D%0A%0A%5Cnand%7B0%7D%7B0%7D%0A%5Cnand%7B0%7D%7B1%7D%0A%5Cnand%7B1%7D%7B0%7D%0A%5Cnand%7B1%7D%7B1%7D%0A%5Cend%7Bdocument%7D)

LaTeX가 튜링 완전하다는 사실을 알면 무수한 가능성이 열립니다. 이런 코드는 LaTeX의 백엔드에서 페이지와 그림 번호를 추적하거나, 떠다니는 요소를 어디에 배치할지 결정하는 일 등에 흔히 사용됩니다. 복잡한 문서 레이아웃을 단순화하는 데 여러분의 이점이 될 수 있는 도구입니다.

이 글을 마치며, LaTeX 프로그래밍과 튜링 기계의 예시에 대한 추가 읽을거리를 남겨 두겠습니다.

#### LaTeX 프로그래밍 예제

* [LaTeX에서의 맨델브로 집합](http://warp.povusers.org/MandScripts/latex.html) . 이 예제에 특별히 감사드립니다. 이 코드는 제 Fibonacci 명령을 작성하는 동안 유용한 예제였습니다.
* [LaTeX의 튜링 기계: 후속 글](http://pbelmans.ncag.info/blog/2010/12/12/a-turing-machine-in-latex-follow-u/) 참고: 이 글을 다른 콘텐츠 호스팅 시스템으로 옮기면서, 원문에서 참조하던 사이트(<http://en.literateprograms.org/Turing_machine_simulator_(LaTeX))> 에 더 이상 접근할 수 없다는 것을 확인했기 때문에, 그 링크를 다른 저자의 후속 글로 대체했습니다.
* [TeX 명령어에 관한 위키북](http://en.wikibooks.org/wiki/Category:TeX)
* [프로그래밍 대회에서의 LaTeX](http://sdh33b.blogspot.com/2008/07/icfp-contest-2008.html). LaTeX로 만든 화성 탐사 로버 컨트롤러가 더 일반적인 여러 프로그래밍 언어로 제출된 작품들을 제쳤습니다.

### 뜻밖의 장소의 튜링 기계

* [콘웨이의 생명 게임은 튜링 완전하다](http://rendell-attic.org/gol/utm/index.htm). 여기에 튜링 기계의 구현이 있습니다.
* [룰 110](http://en.wikipedia.org/wiki/Rule_110) 는 튜링 완전한 1차원 셀룰러 오토마타입니다.
* 마인크래프트(비디오 게임)는 튜링 완전합니다. 여러 예제가 만들어졌으므로, 다음 링크는 단지 [관련 YouTube 검색 결과 페이지입니다](http://www.youtube.com/results?search_query=minecraft+turing+machine)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/ko/in-depth-articles/31-latex-is-more-powerful-than-you-think-computing-the-fibonacci-numbers-and-turing-completeness.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
