Problem Summary

Let \(C(n)\) be the number of Hamiltonian cycles on the Sierpinski graph \(S_n\) described in the problem. We are asked to compute

$$C(C(C(10000))) \pmod{13^8}.$$

The direct values explode immediately, so the only viable route is:

$$\text{graph recurrence} \Longrightarrow \text{closed form} \Longrightarrow \text{modular exponent reduction}.$$

Mathematical Approach

1) Decompose \(S_{n+1}\) into three copies of \(S_n\).

The graph \(S_{n+1}\) consists of three corner-sharing copies of \(S_n\). A Hamiltonian cycle on \(S_{n+1}\) cannot stay closed inside one copy; it must enter each copy through one shared corner and leave through the other shared corner. Therefore each copy contributes a Hamiltonian path between two corner vertices.

Let \(P(n)\) denote the number of such corner-to-corner Hamiltonian paths in \(S_n\) for a fixed ordered copy position. Then the three copies are independent once their corner roles are fixed, so

$$C(n+1)=P(n)^3.$$

2) Why \(P(n)=3C(n)\).

Inside one copy of \(S_n\), a Hamiltonian path is obtained from a Hamiltonian cycle by choosing which one of the three outer corners plays the role of the “unused outer corner” when the copy is embedded into the next level. There are exactly three symmetric choices, and each choice converts bijectively between the cycle state and the required corner-to-corner path state. Hence

$$P(n)=3C(n).$$

Substituting into the previous relation gives the recurrence used by the solver:

$$C(n+1)=(3C(n))^3,\qquad C(3)=8.$$

As a quick check,

$$C(4)=(3\cdot 8)^3=24^3=13824,$$

which matches the iterative checkpoint in the code.

3) Closed form.

Write

$$C(n)=8\cdot 12^{e_n}\qquad (n\ge 3).$$

Then

$$C(n+1)=(3C(n))^3=(24\cdot 12^{e_n})^3=8\cdot 12^{3e_n+3},$$

so the exponents satisfy

$$e_{n+1}=3e_n+3,\qquad e_3=0.$$

This linear recurrence solves to

$$e_n=\frac{3^{n-2}-3}{2}.$$

Therefore

$$C(n)=8\cdot 12^{(3^{n-2}-3)/2}.$$

For example, for \(n=5\),

$$e_5=\frac{3^3-3}{2}=12,\qquad C(5)=8\cdot12^{12}=71328803586048,$$

again exactly the checkpoint used by the implementation.

4) Reduce the outer power modulo \(13^k\).

To compute \(C(n)\bmod 13^k\), we need the multiplicative order of \(12\) modulo \(13^k\). Since

$$12\equiv -1 \pmod{13},$$

its order modulo \(13\) is \(2\). Also

$$12^2-1=143=11\cdot 13,$$

so only one factor of \(13\) divides \(12^2-1\). The standard lifting rule for orders over odd prime powers then gives

$$\operatorname{ord}_{13^k}(12)=2\cdot 13^{k-1}.$$

Hence the exponent only matters modulo

$$2\cdot 13^{k-1}.$$

5) Why the code computes \(3^{n-2}\) modulo \(4\cdot 13^{k-1}\).

The exponent is

$$e_n=\frac{3^{n-2}-3}{2}.$$

We must divide by \(2\) after reducing modulo the exponent period. To do this safely, compute

$$3^{n-2}\pmod{4\cdot 13^{k-1}},$$

then subtract \(3\), which is always even, and only then divide by \(2\). This yields

$$e_n \pmod{2\cdot 13^{k-1}}.$$

6) How much of \(n\) do we really need?

Now the inner task is to compute \(3^{n-2}\) modulo \(4\cdot 13^{k-1}\). Since \(\gcd(3,4\cdot 13^{k-1})=1\), the exponent \(n-2\) may be reduced modulo the Carmichael period of that modulus.

For \(k\ge 2\),

$$\lambda(4\cdot 13^{k-1})=\operatorname{lcm}(\lambda(4),\lambda(13^{k-1}))=\operatorname{lcm}(2,12\cdot 13^{k-2})=12\cdot 13^{k-2}.$$

So to compute \(C(n)\bmod 13^k\), it is enough to know

$$n \pmod{12\cdot 13^{k-2}},$$

plus whether \(n\le 2\). For the huge nested values here, \(n\) is certainly large, so only the residue matters.

7) Why CRT appears.

For every \(n\ge 4\), the recurrence shows that \(C(n)\) is divisible by \(12\), because

$$C(n+1)=(3C(n))^3$$

has an obvious factor \(3^3\), and from \(C(4)=24^3\) onward the factor \(4\) is also permanent. Therefore when the next level needs \(n\bmod (12\cdot 13^t)\), we already know

$$n\equiv 0 \pmod{12}.$$

The solver separately computes

$$n\equiv r \pmod{13^t}$$

and combines the two congruences by the Chinese remainder theorem:

$$n\equiv 0 \pmod{12},\qquad n\equiv r \pmod{13^t}\quad \Longrightarrow \quad n\bmod (12\cdot 13^t).$$

8) Nested evaluation chain.

Define

$$a=C(10000),\qquad b=C(a),\qquad c=C(b).$$

To compute \(b \bmod 13^6\), we only need

$$a \bmod (12\cdot 13^4).$$

So the code first computes

$$a \bmod 13^4,$$

then reconstructs \(a \bmod (12\cdot 13^4)\) using CRT and \(a\equiv 0\pmod{12}\).

Similarly, to compute \(c \bmod 13^8\), we only need

$$b \bmod (12\cdot 13^6).$$

So the same trick is applied one more time. This completely avoids ever forming the astronomical integers \(a\) and \(b\).

Worked Checks

The implementation verifies the following checkpoints:

$$C(1)=1,\qquad C(2)=1,\qquad C(3)=8,$$

$$C(4)=13824,\qquad C(5)=71328803586048,$$

$$C(10000)\bmod 10^8 = 37652224,$$

$$C(10000)\bmod 13^8 = 617720485.$$

The final answer is

$$C(C(C(10000)))\bmod 13^8 = 324681947.$$

Algorithm

1) Implement fast modular multiplication and binary exponentiation.

2) Implement the closed-form evaluator

$$C(n)\bmod 13^k=8\cdot 12^{((3^{n-2}-3)/2)\bmod (2\cdot 13^{k-1})}\pmod{13^k},$$

using the \(4\cdot 13^{k-1}\) trick before dividing by \(2\).

3) Use CRT to lift residues from \(13^t\) to \(12\cdot 13^t\).

4) Evaluate the three nested levels with the minimal modulus needed by the next stage.

Complexity Analysis

Everything reduces to a small number of modular exponentiations. Each one costs \(O(\log M)\) modular multiplications for modulus \(M\). So the total runtime is tiny; the difficulty is entirely mathematical, not computational.

Further Reading

  1. Problem page: https://projecteuler.net/problem=312
  2. Chinese remainder theorem: https://en.wikipedia.org/wiki/Chinese_remainder_theorem
  3. Carmichael function: https://en.wikipedia.org/wiki/Carmichael_function

Problemzusammenfassung

Gesucht ist

$$C(C(C(10000))) \pmod{13^8},$$

wobei \(C(n)\) die Anzahl Hamiltonscher Zyklen im Sierpinski-Graphen \(S_n\) ist. Direkte Iteration ist aussichtslos; entscheidend sind Rekursion, geschlossene Form und Modulreduktion.

Mathematischer Ansatz

1) Zerlegung von \(S_{n+1}\). Der Graph \(S_{n+1}\) besteht aus drei eckengeteilten Kopien von \(S_n\). Ein Hamilton-Zyklus im grossen Graphen muss jede Kopie als Hamilton-Pfad zwischen den beiden geteilten Ecken durchlaufen. Sei \(P(n)\) die Anzahl solcher Eck-zu-Eck-Pfade. Dann gilt

$$C(n+1)=P(n)^3.$$

2) Warum \(P(n)=3C(n)\). In einer Kopie von \(S_n\) kann man einen Hamilton-Zyklus auf genau drei symmetrische Arten in den benoetigten Eckpfad umwandeln, je nachdem welche Aussenecke die Rolle der „freien“ Ecke uebernimmt. Das ist bijektiv, also

$$P(n)=3C(n).$$

Somit folgt die Solver-Rekursion

$$C(n+1)=(3C(n))^3,\qquad C(3)=8.$$

3) Geschlossene Form. Mit

$$C(n)=8\cdot 12^{e_n}$$

erhaelt man

$$e_{n+1}=3e_n+3,\qquad e_3=0,$$

also

$$e_n=\frac{3^{n-2}-3}{2},\qquad C(n)=8\cdot 12^{(3^{n-2}-3)/2}.$$

4) Ordnung von \(12\) modulo \(13^k\). Weil \(12\equiv -1\pmod{13}\), ist die Ordnung modulo \(13\) gleich \(2\). Aus \(12^2-1=143=11\cdot13\) folgt per Lifting ueber Primzahlpotenzen

$$\operatorname{ord}_{13^k}(12)=2\cdot 13^{k-1}.$$

Daher muss der Exponent nur modulo \(2\cdot13^{k-1}\) bekannt sein.

5) Warum modulo \(4\cdot13^{k-1}\) gerechnet wird. Da

$$e_n=\frac{3^{n-2}-3}{2},$$

wird zuerst \(3^{n-2}\) modulo \(4\cdot13^{k-1}\) berechnet, dann \(3\) subtrahiert und erst danach durch \(2\) geteilt. So bleibt die Division modulo-sicher.

6) Welche Information ueber \(n\) reicht aus? Fuer die Potenz \(3^{n-2}\) modulo \(4\cdot13^{k-1}\) genuegt \(n-2\) modulo

$$\lambda(4\cdot13^{k-1})=12\cdot13^{k-2}\qquad (k\ge2).$$

Also reicht

$$n \pmod{12\cdot13^{k-2}}.$$

7) Rolle des CRT. Fuer \(n\ge4\) ist \(C(n)\) stets durch \(12\) teilbar. Wenn die naechste Ebene also \(n\bmod(12\cdot13^t)\) braucht, kennt man bereits

$$n\equiv 0\pmod{12}.$$

Dazu kommt der berechnete Rest modulo \(13^t\). Beides wird mit dem chinesischen Restsatz zusammengesetzt.

8) Verschachtelung. Mit

$$a=C(10000),\qquad b=C(a),\qquad c=C(b)$$

braucht man fuer \(b\bmod13^6\) nur \(a\bmod(12\cdot13^4)\), und fuer \(c\bmod13^8\) nur \(b\bmod(12\cdot13^6)\). Genau das implementiert der Code.

Kontrollwerte

Die Implementierung prueft

$$C(1)=1,\quad C(2)=1,\quad C(3)=8,\quad C(4)=13824,\quad C(5)=71328803586048,$$

$$C(10000)\bmod10^8=37652224,\qquad C(10000)\bmod13^8=617720485.$$

Die Endantwort lautet

$$C(C(C(10000)))\bmod13^8=324681947.$$

Komplexitaetsanalyse

Die Arbeit besteht fast nur aus schneller modularer Potenzierung. Jede Stufe kostet \(O(\log M)\) Multiplikationen fuer Modul \(M\). Rechnerisch ist das klein; die Schwierigkeit ist rein arithmetisch.

Weiterfuehrende Hinweise

  1. Problemseite: https://projecteuler.net/problem=312
  2. Chinesischer Restsatz: https://de.wikipedia.org/wiki/Chinesischer_Restsatz
  3. Carmichael-Funktion: https://de.wikipedia.org/wiki/Carmichael-Funktion

Problem Özeti

\(C(n)\), problemde tanimlanan Sierpinski grafindaki Hamilton cycle sayisi olsun. Aradigimiz deger

$$C(C(C(10000))) \pmod{13^8}.$$

Dogrudan iterasyon hemen patlar; cozum zinciri su:

$$\text{graf rekurensi} \Longrightarrow \text{kapali form} \Longrightarrow \text{moduler us indirgeme}.$$

Matematiksel Yaklaşım

1) \(S_{n+1}\), uc kopya \(S_n\)'den kurulur.

\(S_{n+1}\), kose paylasan uc adet \(S_n\) kopyasindan olusur. Buyuk graf icindeki bir Hamilton cycle, her kopyanin icinden kapali bir cycle olarak degil, iki ortak kose arasinda bir Hamilton path olarak gecmek zorundadir. Sabit bir kopya konumu icin bu kose-kose path sayisina \(P(n)\) diyelim. O zaman

$$C(n+1)=P(n)^3.$$

2) Neden \(P(n)=3C(n)\).

Bir \(S_n\) kopyasi icinde gereken corner-to-corner Hamilton path, bir Hamilton cycle'in “hangi dis kosenin bos rol oynadigini” secerek acilmasiyla elde edilir. Uc dis kose oldugu icin tam uc simetrik secim vardir ve bu donusum bijektiftir. Dolayisiyla

$$P(n)=3C(n).$$

Bunu yukaridaki esitlige koyunca kodun kullandigi rekurens cikar:

$$C(n+1)=(3C(n))^3,\qquad C(3)=8.$$

Hizli kontrol:

$$C(4)=(3\cdot 8)^3=24^3=13824.$$

3) Kapali form.

Su sekilde yazalim:

$$C(n)=8\cdot 12^{e_n}\qquad (n\ge 3).$$

O zaman

$$C(n+1)=(3C(n))^3=(24\cdot12^{e_n})^3=8\cdot12^{3e_n+3},$$

yani

$$e_{n+1}=3e_n+3,\qquad e_3=0.$$

Buradan

$$e_n=\frac{3^{n-2}-3}{2}$$

ve dolayisiyla

$$C(n)=8\cdot 12^{(3^{n-2}-3)/2}$$

elde edilir. Ornegin

$$C(5)=8\cdot12^{12}=71328803586048$$

olur; bu da koddaki checkpoint ile aynidir.

4) \(13^k\) modunda dis uste indirgeme.

\(C(n)\bmod 13^k\) icin \(12\)'nin \(13^k\) modundaki carpimsal mertebesini bilmemiz yeterlidir. Cunku

$$12\equiv -1\pmod{13},$$

ve

$$12^2-1=143=11\cdot13.$$

Bu lifting kuralindan

$$\operatorname{ord}_{13^k}(12)=2\cdot 13^{k-1}$$

sonucu gelir. Yani us sadece bu modda onemlidir.

5) Kod neden \(4\cdot13^{k-1}\) modunda \(3^{n-2}\) hesapluyor?

Us

$$e_n=\frac{3^{n-2}-3}{2}$$

oldugu icin, bolme islemini moduler ortamda guvenli yapmak gerekir. Bu yuzden once

$$3^{n-2}\pmod{4\cdot13^{k-1}}$$

hesaplanir, sonra \(3\) cikarilir ve ancak ondan sonra ikiye bolunur. Boylece

$$e_n \pmod{2\cdot13^{k-1}}$$

dogru elde edilir.

6) Aslinda \(n\)'in ne kadarina ihtiyac var?

Simdi ic problem, \(3^{n-2}\)'yi \(4\cdot13^{k-1}\) modunda hesaplamaktir. \(\gcd(3,4\cdot13^{k-1})=1\) oldugu icin us, Carmichael periyoduna gore indirgenebilir:

$$\lambda(4\cdot13^{k-1})=12\cdot13^{k-2}\qquad (k\ge2).$$

Dolayisiyla \(C(n)\bmod 13^k\) icin yalnizca

$$n \pmod{12\cdot13^{k-2}}$$

yeterlidir.

7) CRT neden lazim?

\(n\ge4\) icin \(C(n)\) her zaman \(12\)'ye bolunur. Cunku \(C(4)=24^3\) ve rekurens bu carpanlari korur. Demek ki bir sonraki seviye \(n\bmod(12\cdot13^t)\) istediginde, zaten

$$n\equiv 0\pmod{12}$$

biliyoruz. Ayrica kod bize

$$n\equiv r\pmod{13^t}$$

verir. Bu iki kongruens CRT ile birlestirilir.

8) Ic ice hesap zinciri.

Su sekilde tanimlayalim:

$$a=C(10000),\qquad b=C(a),\qquad c=C(b).$$

\(b\bmod13^6\) icin sadece

$$a\bmod(12\cdot13^4)$$

gerekir. Bu nedenle kod once \(a\bmod13^4\)'u bulur, sonra \(a\equiv0\pmod{12}\) bilgisiyle CRT uygular. Son asamada da ayni fikirle \(b\bmod(12\cdot13^6)\) uretilir ve buradan

$$c=C(b)\bmod13^8$$

hesaplanir.

Calisan Kontroller

Kod su kontrol degerlerini dogrular:

$$C(1)=1,\qquad C(2)=1,\qquad C(3)=8,\qquad C(4)=13824,$$

$$C(5)=71328803586048,$$

$$C(10000)\bmod10^8=37652224,$$

$$C(10000)\bmod13^8=617720485.$$

Nihai cevap ise

$$C(C(C(10000)))\bmod13^8=324681947.$$

Algoritma

1) Hizli moduler carpim ve binary exponentiation uygula.

2) Kapali formu kullanarak \(C(n)\bmod13^k\) hesaplayicisi yaz.

3) \(n\bmod(12\cdot13^t)\) icin CRT ile mod \(12\) ve mod \(13^t\) bilgilerini birlestir.

4) Ic ice uc seviyeyi, bir sonrakinin ihtiyac duydugu en kucuk modlarla sirayla hesapla.

Karmaşıklık Analizi

Butun agirlik hizli us alma islemlerindedir. Her bir mod \(M\) icin maliyet \(O(\log M)\) moduler carpimdir. Dolayisiyla runtime cok kucuktur; asil zor kisim matematiksel indirgemedir.

Ileri Okuma

  1. Problem metni: https://projecteuler.net/problem=312
  2. Cin Kalan Teoremi: https://tr.wikipedia.org/wiki/Çin_kalan_teoremi
  3. Carmichael fonksiyonu: https://en.wikipedia.org/wiki/Carmichael_function

Resumen del Problema

Sea \(C(n)\) el numero de ciclos hamiltonianos del grafo de Sierpinski \(S_n\). Debemos calcular

$$C(C(C(10000))) \pmod{13^8}.$$

Los valores crecen demasiado rapido, asi que la solucion real es:

$$\text{recurrencia del grafo} \Longrightarrow \text{formula cerrada} \Longrightarrow \text{reduccion modular del exponente}.$$

Enfoque Matematico

1) Descomposicion de \(S_{n+1}\). El grafo \(S_{n+1}\) se forma con tres copias de \(S_n\) que comparten vertices de esquina. Un ciclo hamiltoniano global debe atravesar cada copia como un camino hamiltoniano entre las dos esquinas compartidas. Si \(P(n)\) cuenta esos caminos esquina-a-esquina, entonces

$$C(n+1)=P(n)^3.$$

2) Por que \(P(n)=3C(n)\). Dentro de una copia, un camino esquina-a-esquina se obtiene a partir de un ciclo hamiltoniano eligiendo cual de las tres esquinas exteriores desempena el papel de “esquina libre” al incrustar la copia en el siguiente nivel. Hay exactamente tres elecciones simetricas, y la correspondencia es biyectiva. Por tanto,

$$P(n)=3C(n),$$

y la recurrencia queda

$$C(n+1)=(3C(n))^3,\qquad C(3)=8.$$

3) Formula cerrada. Escribimos

$$C(n)=8\cdot 12^{e_n}\qquad (n\ge3).$$

Entonces

$$e_{n+1}=3e_n+3,\qquad e_3=0,$$

de donde

$$e_n=\frac{3^{n-2}-3}{2},\qquad C(n)=8\cdot 12^{(3^{n-2}-3)/2}.$$

4) Orden de \(12\) modulo \(13^k\). Como \(12\equiv -1\pmod{13}\), su orden modulo \(13\) es \(2\). Y como

$$12^2-1=143=11\cdot13,$$

la elevacion del orden a potencias de \(13\) da

$$\operatorname{ord}_{13^k}(12)=2\cdot13^{k-1}.$$

5) Por que aparece \(4\cdot13^{k-1}\). El exponente es

$$e_n=\frac{3^{n-2}-3}{2}.$$

Para dividir por \(2\) sin ambiguedad modular, primero se calcula \(3^{n-2}\) modulo \(4\cdot13^{k-1}\), luego se resta \(3\), y solo despues se divide por \(2\).

6) Cuanto de \(n\) hace falta? Para calcular \(3^{n-2}\) modulo \(4\cdot13^{k-1}\) basta conocer el exponente modulo

$$\lambda(4\cdot13^{k-1})=12\cdot13^{k-2}\qquad (k\ge2).$$

Asi, para obtener \(C(n)\bmod13^k\), basta con

$$n \pmod{12\cdot13^{k-2}}.$$

7) Uso del CRT. Para todo \(n\ge4\), \(C(n)\) es divisible por \(12\). Entonces, cuando el siguiente nivel necesita \(n\bmod(12\cdot13^t)\), ya sabemos

$$n\equiv0\pmod{12}.$$

El codigo calcula ademas \(n\bmod13^t\) y combina ambas congruencias mediante el teorema chino del resto.

8) Cadena anidada. Sea

$$a=C(10000),\qquad b=C(a),\qquad c=C(b).$$

Para calcular \(b\bmod13^6\) solo hace falta \(a\bmod(12\cdot13^4)\). Para calcular \(c\bmod13^8\) solo hace falta \(b\bmod(12\cdot13^6)\). Esa es exactamente la reduccion aplicada por el solver.

Comprobaciones

La implementacion verifica

$$C(1)=1,\quad C(2)=1,\quad C(3)=8,\quad C(4)=13824,\quad C(5)=71328803586048,$$

$$C(10000)\bmod10^8=37652224,\qquad C(10000)\bmod13^8=617720485.$$

El resultado final es

$$C(C(C(10000)))\bmod13^8=324681947.$$

Complejidad

Todo se reduce a unas pocas potenciaciones modulares rapidas. Cada una cuesta \(O(\log M)\) multiplicaciones modulares para modulo \(M\). El reto es teorico; el tiempo de computo es minimo.

Lecturas

  1. Problema: https://projecteuler.net/problem=312
  2. Teorema chino del resto: https://es.wikipedia.org/wiki/Teorema_chino_del_resto
  3. Funcion de Carmichael: https://es.wikipedia.org/wiki/Función_de_Carmichael

问题概述

设 \(C(n)\) 是题目中 Sierpinski 图 \(S_n\) 的 Hamilton 回路数。目标是求

$$C(C(C(10000))) \pmod{13^8}.$$

直接递推完全不可行,因此真正的路线是:

$$\text{图递推} \Longrightarrow \text{闭式} \Longrightarrow \text{指数模周期压缩}.$$

数学方法

1) 分解 \(S_{n+1}\). 图 \(S_{n+1}\) 由三个共享角点的 \(S_n\) 副本组成。一个全局 Hamilton 回路在每个副本中都必须表现为“两个共享角之间的 Hamilton 路径”。若这种角到角路径数记为 \(P(n)\),则

$$C(n+1)=P(n)^3.$$

2) 为什么 \(P(n)=3C(n)\). 在单个副本中,这种角到角路径可以看成把一个 Hamilton 回路“打开”,并指定三个外角中哪一个充当下一层拼接时的“空角”。三种选择完全对称,而且构成双射,所以

$$P(n)=3C(n).$$

于是得到代码使用的递推

$$C(n+1)=(3C(n))^3,\qquad C(3)=8.$$

3) 闭式。 写成

$$C(n)=8\cdot 12^{e_n}\qquad (n\ge3).$$

$$e_{n+1}=3e_n+3,\qquad e_3=0,$$

从而

$$e_n=\frac{3^{n-2}-3}{2},\qquad C(n)=8\cdot 12^{(3^{n-2}-3)/2}.$$

4) \(12\) 在 \(13^k\) 下的阶。

因为

$$12\equiv -1\pmod{13},$$

所以模 \(13\) 的阶是 \(2\)。再由

$$12^2-1=143=11\cdot13$$

可知提升到 \(13\) 的高次幂时,阶按 \(13^{k-1}\) 放大,因此

$$\operatorname{ord}_{13^k}(12)=2\cdot 13^{k-1}.$$

5) 为什么代码先算模 \(4\cdot13^{k-1}\).

指数是

$$e_n=\frac{3^{n-2}-3}{2}.$$

为了在模意义下安全地“除以 2”,代码先计算

$$3^{n-2}\pmod{4\cdot13^{k-1}},$$

再减去 \(3\),最后再除以 \(2\)。这样可以正确得到

$$e_n \pmod{2\cdot13^{k-1}}.$$

6) 实际只需要知道 \(n\) 的什么信息?

由于 \(\gcd(3,4\cdot13^{k-1})=1\),指数 \(n-2\) 可以按 Carmichael 周期缩减:

$$\lambda(4\cdot13^{k-1})=12\cdot13^{k-2}\qquad (k\ge2).$$

因此求 \(C(n)\bmod13^k\) 只需要知道

$$n \pmod{12\cdot13^{k-2}}.$$

7) 为什么需要 CRT.

对所有 \(n\ge4\),都有 \(C(n)\equiv0\pmod{12}\)。所以当下一层需要 \(n\bmod(12\cdot13^t)\) 时,我们已经知道一部分:

$$n\equiv0\pmod{12}.$$

代码再计算 \(n\bmod13^t\),然后用中国剩余定理合并这两个同余。

8) 三层嵌套如何处理。

$$a=C(10000),\qquad b=C(a),\qquad c=C(b).$$

要算 \(b\bmod13^6\),只需知道

$$a\bmod(12\cdot13^4).$$

要算 \(c\bmod13^8\),只需知道

$$b\bmod(12\cdot13^6).$$

这就是代码逐层降低模数规模的原因。

检查值

实现验证了

$$C(1)=1,\quad C(2)=1,\quad C(3)=8,\quad C(4)=13824,\quad C(5)=71328803586048,$$

$$C(10000)\bmod10^8=37652224,\qquad C(10000)\bmod13^8=617720485.$$

最终答案为

$$C(C(C(10000)))\bmod13^8=324681947.$$

复杂度分析

全部计算基本只由少量快速幂组成。每次快速幂成本为 \(O(\log M)\)。因此运行时间极小,真正困难的是数论化简而不是算力。

延伸阅读

  1. 题目页面: https://projecteuler.net/problem=312
  2. 中国剩余定理: https://zh.wikipedia.org/wiki/中国剩余定理
  3. Carmichael 函数: https://zh.wikipedia.org/wiki/卡达莫函数

Краткое описание

Пусть \(C(n)\) - число гамильтоновых циклов в графе Серпинского \(S_n\). Нужно найти

$$C(C(C(10000))) \pmod{13^8}.$$

Прямое разворачивание невозможно, поэтому решение строится так:

$$\text{рекурсия графа} \Longrightarrow \text{закрытая формула} \Longrightarrow \text{сжатие показателей по модулю}.$$

Математический подход

1) Разложение \(S_{n+1}\). Граф \(S_{n+1}\) состоит из трех копий \(S_n\), попарно разделяющих угловые вершины. Гамильтонов цикл большого графа проходит через каждую копию как через гамильтонов путь между двумя общими углами. Если \(P(n)\) - число таких угловых путей, то

$$C(n+1)=P(n)^3.$$

2) Почему \(P(n)=3C(n)\). Внутри одной копии требуемый угловой путь получается из гамильтонова цикла выбором одной из трех внешних вершин, играющей роль “свободного угла” при склейке на следующем уровне. Выборов ровно три, и соответствие биективно. Поэтому

$$P(n)=3C(n),$$

и мы получаем

$$C(n+1)=(3C(n))^3,\qquad C(3)=8.$$

3) Закрытая формула. Пишем

$$C(n)=8\cdot 12^{e_n}\qquad (n\ge3).$$

Тогда

$$e_{n+1}=3e_n+3,\qquad e_3=0,$$

откуда

$$e_n=\frac{3^{n-2}-3}{2},\qquad C(n)=8\cdot 12^{(3^{n-2}-3)/2}.$$

4) Порядок числа \(12\) по модулю \(13^k\).

Так как

$$12\equiv -1\pmod{13},$$

его порядок по модулю \(13\) равен \(2\). Кроме того,

$$12^2-1=143=11\cdot13,$$

поэтому при подъеме к степеням \(13\) порядок становится

$$\operatorname{ord}_{13^k}(12)=2\cdot13^{k-1}.$$

5) Зачем нужен модуль \(4\cdot13^{k-1}\).

Показатель степени равен

$$e_n=\frac{3^{n-2}-3}{2}.$$

Чтобы корректно разделить на \(2\) после взятия по модулю, сначала вычисляется \(3^{n-2}\) по модулю \(4\cdot13^{k-1}\), затем вычитается \(3\), и только потом выполняется деление на \(2\).

6) Что реально нужно знать о \(n\).

Поскольку \(\gcd(3,4\cdot13^{k-1})=1\), показатель \(n-2\) можно сокращать по функции Кармайкла:

$$\lambda(4\cdot13^{k-1})=12\cdot13^{k-2}\qquad (k\ge2).$$

Следовательно, для вычисления \(C(n)\bmod13^k\) достаточно знать

$$n \pmod{12\cdot13^{k-2}}.$$

7) Откуда берется CRT.

Для всех \(n\ge4\) значение \(C(n)\) делится на \(12\). Значит, когда следующий уровень требует \(n\bmod(12\cdot13^t)\), уже известно

$$n\equiv0\pmod{12}.$$

Остается вычислить \(n\bmod13^t\) и склеить оба сравнения китайской теоремой об остатках.

8) Цепочка вложений.

Пусть

$$a=C(10000),\qquad b=C(a),\qquad c=C(b).$$

Чтобы найти \(b\bmod13^6\), достаточно \(a\bmod(12\cdot13^4)\). Чтобы найти \(c\bmod13^8\), достаточно \(b\bmod(12\cdot13^6)\). Именно это и делает программа.

Проверки

Код проверяет

$$C(1)=1,\quad C(2)=1,\quad C(3)=8,\quad C(4)=13824,\quad C(5)=71328803586048,$$

$$C(10000)\bmod10^8=37652224,\qquad C(10000)\bmod13^8=617720485.$$

Финальный ответ:

$$C(C(C(10000)))\bmod13^8=324681947.$$

Сложность

Практически вся работа - это несколько быстрых возведений в степень по модулю. Каждое стоит \(O(\log M)\) умножений. Поэтому вычисление очень быстрое; трудность здесь чисто арифметическая.

Дополнительные материалы

  1. Условие: https://projecteuler.net/problem=312
  2. Китайская теорема об остатках: https://ru.wikipedia.org/wiki/Китайская_теорема_об_остатках
  3. Функция Кармайкла: https://ru.wikipedia.org/wiki/Функция_Кармайкла

ملخص المسألة

لتكن \(C(n)\) عدد الدورات الهاملتونية في مخطط Sierpinski \(S_n\). نريد حساب

$$C(C(C(10000))) \pmod{13^8}.$$

القيم تنفجر بسرعة شديدة، لذلك لا بد من المرور عبر ثلاث طبقات: علاقة عودية على الرسوم، ثم صيغة مغلقة، ثم اختزال أسي modulo قوى \(13\).

المنهج الرياضي

1) تفكيك \(S_{n+1}\). الرسم \(S_{n+1}\) يتكون من ثلاث نسخ من \(S_n\) تتشارك رؤوس الزوايا. أي دورة هاملتونية على الرسم الكبير تمر عبر كل نسخة باعتبارها مسارًا هاملتونيًا بين زاويتين مشتركتين. إذا رمزنا لعدد هذه المسارات بـ \(P(n)\)، فإن

$$C(n+1)=P(n)^3.$$

2) لماذا \(P(n)=3C(n)\). داخل نسخة واحدة، يمكن الحصول على المسار المطلوب من دورة هاملتونية باختيار أي زاوية خارجية من الزوايا الثلاث لتلعب دور “الزاوية الحرة” عند الربط في المستوى التالي. توجد ثلاث اختيارات متناظرة تمامًا، والتحويل تقابلي، ولذلك

$$P(n)=3C(n).$$

ومن ثم نحصل على العودية المستعملة في الكود:

$$C(n+1)=(3C(n))^3,\qquad C(3)=8.$$

3) الصيغة المغلقة. نكتب

$$C(n)=8\cdot 12^{e_n}\qquad (n\ge3).$$

عندئذ

$$e_{n+1}=3e_n+3,\qquad e_3=0,$$

ومنها

$$e_n=\frac{3^{n-2}-3}{2},\qquad C(n)=8\cdot 12^{(3^{n-2}-3)/2}.$$

4) رتبة \(12\) modulo \(13^k\).

بما أن

$$12\equiv -1\pmod{13},$$

فرتبته modulo \(13\) هي \(2\). ومع

$$12^2-1=143=11\cdot13,$$

فإن رفع الرتبة إلى قوى \(13\) يعطي

$$\operatorname{ord}_{13^k}(12)=2\cdot 13^{k-1}.$$

5) لماذا نحسب modulo \(4\cdot13^{k-1}\).

الاس هو

$$e_n=\frac{3^{n-2}-3}{2}.$$

ولكي نقسم على \(2\) بشكل صحيح بعد الاختزال، نحسب أولًا

$$3^{n-2}\pmod{4\cdot13^{k-1}},$$

ثم نطرح \(3\)، وبعد ذلك فقط نقسم على \(2\). بهذه الطريقة نحصل على

$$e_n \pmod{2\cdot13^{k-1}}.$$

6) ما المقدار الذي نحتاجه فعليًا من \(n\)؟

لأن \(\gcd(3,4\cdot13^{k-1})=1\)، يمكن اختزال الاس \(n-2\) بواسطة دالة كارمايكل:

$$\lambda(4\cdot13^{k-1})=12\cdot13^{k-2}\qquad (k\ge2).$$

إذن يكفي لمعرفة \(C(n)\bmod13^k\) أن نعرف

$$n \pmod{12\cdot13^{k-2}}.$$

7) لماذا يظهر CRT.

لكل \(n\ge4\)، تكون \(C(n)\) قابلة للقسمة على \(12\). لذلك حين يحتاج المستوى التالي إلى \(n\bmod(12\cdot13^t)\)، فنحن نعرف مسبقًا

$$n\equiv0\pmod{12}.$$

ويبقى فقط حساب \(n\bmod13^t\)، ثم دمج التطابقين بواسطة مبرهنة البواقي الصينية.

8) سلسلة التداخل.

لنكتب

$$a=C(10000),\qquad b=C(a),\qquad c=C(b).$$

لحساب \(b\bmod13^6\) يكفي معرفة

$$a\bmod(12\cdot13^4),$$

ولحساب \(c\bmod13^8\) يكفي معرفة

$$b\bmod(12\cdot13^6).$$

وهذا بالضبط ما يفعله البرنامج.

نقاط تحقق

الكود يتحقق من

$$C(1)=1,\quad C(2)=1,\quad C(3)=8,\quad C(4)=13824,\quad C(5)=71328803586048,$$

$$C(10000)\bmod10^8=37652224,\qquad C(10000)\bmod13^8=617720485.$$

والنتيجة النهائية هي

$$C(C(C(10000)))\bmod13^8=324681947.$$

تحليل التعقيد

كل العمل تقريبًا عبارة عن عدد قليل من عمليات الرفع السريع للاس modulo. كلفة كل عملية هي \(O(\log M)\) ضربات modularية. لذلك الحساب نفسه سريع جدًا؛ الصعوبة الحقيقية رياضية وليست حسابية.

مراجع إضافية

  1. صفحة المسألة: https://projecteuler.net/problem=312
  2. مبرهنة البواقي الصينية: https://ar.wikipedia.org/wiki/مبرهنة_البواقي_الصينية
  3. دالة كارمايكل: https://en.wikipedia.org/wiki/Carmichael_function