[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Số nguyên tố



Gửi các bạn đoạn mã bảng số nguyên tố

\documentclass{article}
%
\makeatletter
\def\primes#1#2{{%
  \def\comma{\def\comma{, }}%
  \[email protected]\@ne\@tempcntb#2\relax\@curtab#1\relax
  \@primes}}
\def\@primes{\loop\advance\[email protected]\@ne
\expandafter\ifx\csname p-\the\[email protected]\endcsname\relax
\ifnum\@tempcntb<\[email protected]\else
  \ifnum\[email protected]<\@curtab\else\comma\the\[email protected]\fi\fi\else\repeat
\@tempcnta\[email protected]\loop\advance\@tempcnta\[email protected]
\expandafter\let\csname p-\the\@tempcnta\endcsname\@ne
\ifnum\@tempcnta<\@tempcntb\repeat
\ifnum\@tempcntb>\[email protected]\expandafter\@primes\fi}
\makeatother 

  \newif\ifprime \newif\ifunknown % boolean variables
\newcount\n \newcount\p \newcount\d \newcount\a % integer variables
\def\primes#1{2,~3% assume that #1 is at least 3
\n=#1 \advance\n by-2 % n more to go
\p=5 % odd primes starting with p
\loop\ifnum\n>0 \printifprime\advance\p by2 \repeat}
\def\printp{, % we will invoke \printp if p is prime
\ifnum\n=1 and~\fi % ‘and’ precedes the last value
\number\p \advance\n by -1 }
\def\printifprime{\testprimality \ifprime\printp\fi}
\def\testprimality{{\d=3 \global\primetrue
\loop\trialdivision \ifunknown\advance\d by2 \repeat}}
\def\trialdivision{\a=\p \divide\a by\d
\ifnum\a>\d \unknowntrue\else\unknownfalse\fi
\multiply\a by\d
\ifnum\a=\p \global\primefalse\unknownfalse\fi}
%
\begin{document}


The first 1000 prime numbers are \primes{1000}


\end{document}