Problem Summary

Let \(T(m,n)\) be the number of binomial coefficients

$$\binom{i}{n}$$

that are divisible by \(10\), for

$$n\le i\lt m.$$

We are given

$$T(10^9,10^7-10)=989697000,$$

and we must compute

$$T(10^{18},10^{12}-10).$$

Mathematical Approach

1) Shift from \(i\) to \(x=i-n\).

Write

$$i=n+x,$$

so \(x\) runs through

$$0\le x\lt L,\qquad L=m-n.$$

Then the problem is to count how many values of

$$\binom{n+x}{n}$$

are divisible by \(10\).

2) Divisible by \(10\) means divisible by both \(2\) and \(5\).

So we study the prime valuations

$$v_2\!\left(\binom{n+x}{n}\right),\qquad v_5\!\left(\binom{n+x}{n}\right).$$

The coefficient is divisible by \(10\) exactly when both are positive.

3) Kummer's theorem turns valuations into carry counts.

For a prime \(p\), Kummer says

$$v_p\!\left(\binom{n+x}{n}\right)=\text{number of carries when adding }n\text{ and }x\text{ in base }p.$$

Therefore

$$\binom{n+x}{n}\not\equiv0\pmod p$$

if and only if the base-\(p\) addition \(n+x\) has no carry at all.

4) No-carry condition as a digit inequality.

Let the base-\(p\) digits be

$$n=\sum n_j p^j,\qquad x=\sum x_j p^j.$$

No carry is equivalent to

$$n_j+x_j\le p-1\qquad\text{for every }j,$$

or, equivalently,

$$x_j\le p-1-n_j\qquad\text{for every digit }j.$$

This is the Lucas-style digit condition used by the code.

5) Inclusion-exclusion for divisibility by \(10\).

Among the \(L\) candidates \(x\in[0,L)\), define:

$$A_2=\#\{x : \binom{n+x}{n}\not\equiv0\pmod2\},$$

$$A_5=\#\{x : \binom{n+x}{n}\not\equiv0\pmod5\},$$

$$A_{2,5}=\#\{x : \binom{n+x}{n}\text{ is coprime to }10\}.$$

Then the number divisible by \(10\) is

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

So the hard part is to count the non-divisible cases efficiently.

6) Counting \(A_p\) with digit DP.

To count \(A_p\), we must count numbers \(x\) with

$$0\le x\lt L$$

such that every base-\(p\) digit satisfies

$$x_j\le p-1-n_j.$$

This is a standard digit-DP with two states:

tight: the prefix of \(x\) already matches the upper bound \(L-1\),

loose: the prefix is already smaller, so later digits are free up to their carry cap.

The code performs exactly this DP for \(p=2\) and \(p=5\).

7) Special simplification in base \(2\).

In base \(2\), the digit condition becomes:

if a bit of \(n\) is \(1\), the corresponding bit of \(x\) must be \(0\). Hence no-carry in base \(2\) is equivalent to the bitwise condition

$$(x\ \&\ n)=0.$$

The overlap stage of the program uses this extremely cheap test.

8) Counting the overlap \(A_{2,5}\).

This is the set of \(x\lt L\) that satisfy both:

1) no carry in base \(5\),

2) no carry in base \(2\).

The code chooses base \(5\) as the primary generator. It enumerates exactly those \(x\) whose base-5 digits respect

$$x_j\le 4-n_j^{(5)},$$

and then filters them using

$$(x\ \&\ n)=0.$$

To keep this feasible at huge bounds, the base-5 digits are split into low and high blocks, generating two smaller lists whose combinations cover all candidates under \(x\lt L\).

9) Small sanity check.

For small values, the code compares the fast method against a brute-force valuation computation using

$$v_p\!\left(\binom{i}{n}\right)=v_p(i!)-v_p(n!)-v_p((i-n)!).$$

This confirms that the carry-based counting and the inclusion-exclusion formula agree exactly.

Algorithm

1) Set \(L=m-n\) and count all \(x\in[0,L)\).

2) Compute \(A_2\) by digit-DP in base \(2\).

3) Compute \(A_5\) by digit-DP in base \(5\).

4) Compute \(A_{2,5}\) by generating base-5-valid candidates and filtering them with \((x\&n)=0\).

5) Return

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

Complexity Analysis

The single-prime counts \(A_2\) and \(A_5\) are essentially linear in the number of digits. The expensive part is \(A_{2,5}\), but the split-by-block strategy avoids scanning the full interval \([0,L)\), which would be impossible for \(10^{18}\)-scale bounds.

Checks And Final Result

The implementation checks the given sample

$$T(10^9,10^7-10)=989697000,$$

and also cross-checks several smaller cases against brute force.

The final answer is

$$T(10^{18},10^{12}-10)=999998760323313995.$$

Further Reading

  1. Problem page: https://projecteuler.net/problem=322
  2. Kummer's theorem: https://en.wikipedia.org/wiki/Kummer's_theorem
  3. Lucas's theorem: https://en.wikipedia.org/wiki/Lucas's_theorem

Problemzusammenfassung

Gesucht ist die Anzahl der Binomialkoeffizienten

$$\binom{i}{n}$$

mit

$$n\le i\lt m,$$

die durch \(10\) teilbar sind.

Mathematischer Ansatz

1) Verschiebung \(i=n+x\).

Mit

$$i=n+x,\qquad 0\le x\lt L,\qquad L=m-n$$

zaehlen wir also \(\binom{n+x}{n}\).

2) Kummer fuer \(p=2\) und \(p=5\).

Kummer sagt:

$$v_p\!\left(\binom{n+x}{n}\right)=\text{Anzahl der Uebertraege bei }n+x\text{ in Basis }p.$$

Also ist \(\binom{n+x}{n}\) genau dann nicht durch \(p\) teilbar, wenn in Basis \(p\) kein Uebertrag auftritt.

3) Digitbedingung.

Schreibt man

$$n=\sum n_jp^j,\qquad x=\sum x_jp^j,$$

dann bedeutet "kein Uebertrag"

$$x_j\le p-1-n_j\qquad\text{fuer alle Stellen.}$$

4) Inklusion-Exklusion.

Seien \(A_2\), \(A_5\), \(A_{2,5}\) die Anzahlen der \(x\), fuer die \(\binom{n+x}{n}\) nicht durch \(2\), nicht durch \(5\) bzw. durch keines von beiden teilbar ist. Dann

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

5) Berechnung von \(A_2\) und \(A_5\).

Diese Groessen werden per Digit-DP unter der Obergrenze \(x\lt L\) berechnet.

6) Ueberschneidung \(A_{2,5}\).

Der Code erzeugt zuerst alle Kandidaten, die die Basis-5-Bedingung erfuellen, und filtert sie dann mit der binären Bedingung

$$(x\ \&\ n)=0,$$

die genau "kein Uebertrag in Basis 2" bedeutet.

Zur Beschleunigung werden die Basis-5-Stellen in einen niedrigen und einen hohen Block zerlegt.

Algorithmus

1) \(L=m-n\) bilden.

2) \(A_2\) per Digit-DP in Basis 2 berechnen.

3) \(A_5\) per Digit-DP in Basis 5 berechnen.

4) \(A_{2,5}\) ueber Basis-5-Kandidaten + Bitfilter bestimmen.

5) Inklusion-Exklusion anwenden.

Komplexitaetsanalyse

Die Einzelzaehlungen sind linear in der Stellenzahl. Die Ueberschneidung ist der teure Teil, aber die Blockzerlegung vermeidet eine Vollsuche auf \([0,L)\).

Kontrollen Und Endergebnis

Der Code prueft

$$T(10^9,10^7-10)=989697000,$$

und kleinere Faelle per Brute Force. Das Endergebnis lautet

$$999998760323313995.$$

Weiterfuehrende Hinweise

  1. Problem: https://projecteuler.net/problem=322
  2. Satz von Kummer: https://de.wikipedia.org/wiki/Satz_von_Kummer
  3. Satz von Lucas: https://de.wikipedia.org/wiki/Satz_von_Lucas

Problem Özeti

Aranan değer,

$$n\le i\lt m$$

aralığında

$$\binom{i}{n}$$

ifadelerinden kaç tanesinin \(10\)'a bölündüğüdür.

Matematiksel Yaklaşım

1) \(i=n+x\) dönüşümü.

$$i=n+x,\qquad 0\le x\lt L,\qquad L=m-n.$$

Dolayısıyla problem, \(\binom{n+x}{n}\) ifadelerini saymaya iner.

2) 10'a bölünme, 2'ye ve 5'e aynı anda bölünmedir.

Bu yüzden

$$v_2\!\left(\binom{n+x}{n}\right),\qquad v_5\!\left(\binom{n+x}{n}\right)$$

değerlerine bakarız.

3) Kummer teoremi taşıma sayısını verir.

Bir asal \(p\) için

$$v_p\!\left(\binom{n+x}{n}\right)=\text{taban }p\text{ toplamasında }n+x\text{ için oluşan taşıma sayısı}.$$

Demek ki \(\binom{n+x}{n}\)'in \(p\)'ye bölünmemesi, taban \(p\)'de hiç taşıma olmamasıyla aynıdır.

4) Basamak koşulu.

\(n\) ve \(x\)'i taban \(p\)'de

$$n=\sum n_jp^j,\qquad x=\sum x_jp^j$$

şeklinde yazarsak, no-carry koşulu

$$x_j\le p-1-n_j\qquad\text{tum }j\text{ icin}$$

olur.

5) Dahil etme-çıkarma.

\(A_2\), \(A_5\), \(A_{2,5}\) sırasıyla şu sayımlar olsun:

1) \(2\)'ye bölünmeyenler,

2) \(5\)'e bölünmeyenler,

3) ne \(2\)'ye ne \(5\)'e bölünenler.

O zaman

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

6) \(A_2\) ve \(A_5\) nasıl sayılıyor?

Her ikisi de, üst sınır

$$x\lt L$$

altında digit-DP ile sayılır. DP, bir prefix'in üst sınıra eşit gidip gitmediğini tutar ve her basamakta izin verilen en büyük rakamı \(p-1-n_j\) olarak kullanır.

7) İkili tabanda özel sadeleşme.

Taban \(2\)'de no-carry koşulu doğrudan

$$(x\ \&\ n)=0$$

eşdeğerliğine iner. Çünkü \(n\)'nin bir biti \(1\) ise, aynı yerde \(x\)'in biti de \(1\) olamaz.

8) Kesişim \(A_{2,5}\) nasıl bulunuyor?

Kod önce taban \(5\) koşulunu sağlayan adayları üretir. Sonra bunları

$$(x\ \&\ n)=0$$

filtresinden geçirerek aynı zamanda taban \(2\)'de de no-carry olanları sayar. Aday üretimi pahalı olmasın diye taban-5 basamakları düşük ve yüksek bloklara ayrılır.

Algoritma

1) \(L=m-n\) hesapla.

2) \(A_2\)'yi base-2 digit-DP ile bul.

3) \(A_5\)'i base-5 digit-DP ile bul.

4) \(A_{2,5}\)'i base-5 aday üret + bit filtresi ile bul.

5) Sonucu

$$T(m,n)=L-A_2-A_5+A_{2,5}$$

ile döndür.

Karmaşıklık Analizi

Tek asal için digit-DP, basamak sayısına lineerdir. Ağır kısım \(A_{2,5}\)'tir; fakat bloklama sayesinde \([0,L)\) aralığını kaba kuvvet taramaya gerek kalmaz.

Kontroller Ve Nihai Sonuc

Kod verilen örneği doğrular:

$$T(10^9,10^7-10)=989697000.$$

Ayrıca küçük durumlarda brute-force ile çapraz kontrol yapar. Nihai cevap

$$999998760323313995$$

olarak bulunur.

Ileri Okuma

  1. Problem metni: https://projecteuler.net/problem=322
  2. Kummer teoremi: https://tr.wikipedia.org/wiki/Kummer_teoremi
  3. Lucas teoremi: https://tr.wikipedia.org/wiki/Lucas_teoremi

Resumen del Problema

Debemos contar cuantos coeficientes binomiales

$$\binom{i}{n}$$

con

$$n\le i\lt m$$

son divisibles por \(10\).

Enfoque Matematico

1) Cambio \(i=n+x\).

Sea

$$i=n+x,\qquad 0\le x\lt L,\qquad L=m-n.$$

Entonces contamos \(\binom{n+x}{n}\).

2) Kummer para \(p=2\) y \(p=5\).

Para un primo \(p\),

$$v_p\!\left(\binom{n+x}{n}\right)=\text{numero de acarreos al sumar }n\text{ y }x\text{ en base }p.$$

Asi, no ser divisible por \(p\) equivale a que no haya acarreos.

3) Condicion por digitos.

Si

$$n=\sum n_jp^j,\qquad x=\sum x_jp^j,$$

entonces la condicion sin acarreo es

$$x_j\le p-1-n_j.$$

4) Inclusion-exclusion.

Definimos \(A_2\), \(A_5\), \(A_{2,5}\) como los conteos de coeficientes no divisibles por \(2\), no divisibles por \(5\), y coprimos con \(10\). Entonces

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

5) Calculo de \(A_2\) y \(A_5\).

Ambos se obtienen mediante digit-DP con la restriccion \(x\lt L\).

6) Superposicion \(A_{2,5}\).

El programa genera primero los candidatos validos en base \(5\), y luego los filtra con la condicion binaria

$$(x\ \&\ n)=0,$$

que representa ausencia de acarreo en base \(2\).

Algoritmo

1) Poner \(L=m-n\).

2) Contar \(A_2\) con DP en base \(2\).

3) Contar \(A_5\) con DP en base \(5\).

4) Contar \(A_{2,5}\) generando en base \(5\) y filtrando en base \(2\).

5) Aplicar inclusion-exclusion.

Complejidad

Los conteos para un solo primo son lineales en la cantidad de digitos. La interseccion es la parte costosa, y la descomposicion por bloques evita un barrido completo del intervalo.

Comprobaciones Y Resultado Final

El codigo verifica

$$T(10^9,10^7-10)=989697000,$$

ademas de varios casos pequenos por fuerza bruta. El resultado final es

$$999998760323313995.$$

Lecturas

  1. Problema: https://projecteuler.net/problem=322
  2. Teorema de Kummer: https://es.wikipedia.org/wiki/Teorema_de_Kummer
  3. Teorema de Lucas: https://es.wikipedia.org/wiki/Teorema_de_Lucas

问题概述

我们要统计满足

$$n\le i\lt m$$

时的二项式系数

$$\binom{i}{n}$$

中,有多少个能被 \(10\) 整除。

数学方法

1)令 \(i=n+x\)。

于是

$$0\le x\lt L,\qquad L=m-n,$$

问题改写为统计 \(\binom{n+x}{n}\)。

2)Kummer 定理把问题变成“进位”问题。

对素数 \(p\),

$$v_p\!\left(\binom{n+x}{n}\right)=\text{在 }p\text{ 进制下 }n+x\text{ 的进位次数}.$$

所以不被 \(p\) 整除,等价于完全没有进位。

3)按位条件。

$$n=\sum n_jp^j,\qquad x=\sum x_jp^j,$$

则无进位条件就是

$$x_j\le p-1-n_j.$$

4)对 10 做包含-排除。

定义 \(A_2\)、\(A_5\)、\(A_{2,5}\) 分别为“不被 2 整除”“不被 5 整除”“与 10 互素”的计数,则

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

5)\(A_2\) 和 \(A_5\) 用数位 DP。

在上界 \(x\lt L\) 下,按数位做 DP,限制每位不超过 \(p-1-n_j\)。

6)交集 \(A_{2,5}\) 的计算。

代码先生成所有满足 5 进制无进位条件的候选 \(x\),再用二进制条件

$$(x\ \&\ n)=0$$

筛掉不满足 2 进制无进位的项。为提高效率,又把 5 进制位拆成高低两块处理。

算法

1) 计算 \(L=m-n\)。

2) 用 base-2 digit-DP 计算 \(A_2\)。

3) 用 base-5 digit-DP 计算 \(A_5\)。

4) 用“base-5 枚举 + base-2 过滤”计算 \(A_{2,5}\)。

5) 套用包含-排除公式。

复杂度分析

单个素数的数位 DP 与位数近似线性相关。交集部分最重,但分块生成避免了对 \([0,L)\) 的完全遍历。

校验与最终结果

程序验证了

$$T(10^9,10^7-10)=989697000,$$

并对若干小例子做了暴力交叉检查。最终答案是

$$999998760323313995.$$

延伸阅读

  1. 题目页面: https://projecteuler.net/problem=322
  2. Kummer 定理: https://en.wikipedia.org/wiki/Kummer's_theorem
  3. Lucas 定理: https://zh.wikipedia.org/wiki/卢卡斯定理

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

Нужно посчитать число биномиальных коэффициентов

$$\binom{i}{n}$$

для

$$n\le i\lt m,$$

которые делятся на \(10\).

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

1) Подстановка \(i=n+x\).

Тогда

$$0\le x\lt L,\qquad L=m-n,$$

и мы рассматриваем \(\binom{n+x}{n}\).

2) Теорема Куммера.

Для простого \(p\)

$$v_p\!\left(\binom{n+x}{n}\right)=\text{число переносов при сложении }n\text{ и }x\text{ в базе }p.$$

Значит, неделимость на \(p\) равносильна полному отсутствию переносов.

3) Условие на цифры.

Если

$$n=\sum n_jp^j,\qquad x=\sum x_jp^j,$$

то отсутствие переносов означает

$$x_j\le p-1-n_j.$$

4) Включение-исключение для делимости на 10.

Пусть \(A_2\), \(A_5\), \(A_{2,5}\) - количества случаев, когда коэффициент не делится на \(2\), не делится на \(5\), и взаимно прост с \(10\). Тогда

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

5) Вычисление \(A_2\) и \(A_5\).

Они считаются digit-DP под ограничением \(x\lt L\).

6) Пересечение \(A_{2,5}\).

Код сначала генерирует все кандидаты, допустимые в базе \(5\), затем фильтрует их двоичным условием

$$(x\ \&\ n)=0,$$

которое означает отсутствие переносов в базе \(2\). Для ускорения используется разбиение по блокам base-5 цифр.

Алгоритм

1) Вычислить \(L=m-n\).

2) Посчитать \(A_2\) digit-DP в базе 2.

3) Посчитать \(A_5\) digit-DP в базе 5.

4) Найти \(A_{2,5}\) через генерацию base-5 и фильтр base-2.

5) Применить включение-исключение.

Сложность

Одиночные подсчеты линейны по числу разрядов. Наиболее тяжелая часть - пересечение, но блочная генерация делает задачу выполнимой даже при границе порядка \(10^{18}\).

Проверки И Итоговый Ответ

Программа проверяет

$$T(10^9,10^7-10)=989697000,$$

и несколько малых случаев против brute force. Итоговый ответ:

$$999998760323313995.$$

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

  1. Условие: https://projecteuler.net/problem=322
  2. Теорема Куммера: https://ru.wikipedia.org/wiki/Теорема_Кюммера
  3. Теорема Люка: https://ru.wikipedia.org/wiki/Теорема_Люка

ملخص المسألة

نريد عدّ معاملات ثنائية الحد

$$\binom{i}{n}$$

لـ

$$n\le i\lt m,$$

التي تقبل القسمة على \(10\).

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

1) التعويض \(i=n+x\).

عندئذ

$$0\le x\lt L,\qquad L=m-n,$$

فتصبح المسألة دراسة \(\binom{n+x}{n}\).

2) مبرهنة Kummer.

بالنسبة إلى أولي \(p\)، لدينا

$$v_p\!\left(\binom{n+x}{n}\right)=\text{عدد الحملات عند جمع }n\text{ و }x\text{ في الأساس }p.$$

إذًا عدم القسمة على \(p\) يكافئ عدم وجود أي حمل.

3) الشرط الرقمي.

إذا كتبنا

$$n=\sum n_jp^j,\qquad x=\sum x_jp^j,$$

فإن شرط عدم الحمل هو

$$x_j\le p-1-n_j.$$

4) الشمول والاستبعاد للقسمة على \(10\).

لتكن \(A_2\)، \(A_5\)، \(A_{2,5}\) أعداد القيم التي لا ينقسم فيها المعامل على \(2\)، أو لا ينقسم على \(5\)، أو يكون أوليًا مع \(10\). عندئذ

$$T(m,n)=L-A_2-A_5+A_{2,5}.$$

5) حساب \(A_2\) و\(A_5\).

يتم ذلك بواسطة digit-DP مع القيد \(x\lt L\).

6) حساب التقاطع \(A_{2,5}\).

يولد البرنامج أولاً جميع المرشحين الموافقين لقيود الأساس \(5\)، ثم يرشحهم بشرط الأساس \(2\)

$$(x\ \&\ n)=0,$$

والذي يعني عدم وجود حمل في الجمع الثنائي. كما يُقسَّم التوليد بحسب كتل من خانات الأساس \(5\) لتسريع التنفيذ.

الخوارزمية

1) نحسب \(L=m-n\).

2) نحسب \(A_2\) بـ digit-DP في الأساس \(2\).

3) نحسب \(A_5\) بـ digit-DP في الأساس \(5\).

4) نحسب \(A_{2,5}\) عبر توليد base-5 ثم ترشيح base-2.

5) نطبق صيغة الشمول والاستبعاد.

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

عدّ كل أساس منفرد شبه خطي في عدد الخانات. أما الجزء الأثقل فهو التقاطع، لكن التقسيم إلى كتل يمنع الحاجة إلى استعراض المجال الكامل \([0,L)\).

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

يتحقق البرنامج من

$$T(10^9,10^7-10)=989697000,$$

ومن عدة حالات صغيرة بالمقارنة مع brute force. والنتيجة النهائية هي

$$999998760323313995.$$

مراجع إضافية

  1. صفحة المسألة: https://projecteuler.net/problem=322
  2. مبرهنة Kummer: https://en.wikipedia.org/wiki/Kummer's_theorem
  3. مبرهنة Lucas: https://ar.wikipedia.org/wiki/مبرهنة_لوكاس