0

enter image description hereI am trying to generate a list of examples using PythonTeX and pgffor but this doesn't seem to work ?! The same example is repeated 5 times instead of getting 20 different examples. What's wrong in the MWE below ? Thank you.

\documentclass[12pt]{article}
\usepackage{amsmath, pgffor}
\usepackage{pythontex}
\pagestyle{empty}
\begin{document}
\begin{pycode}
import random 

def gcd(a,b):
   if(b==0):
      return a
   else:
      return gcd(b,a%b)

c = random.randint(400,1000)
d = random.randint(50,400)
p = gcd(c,d)
\end{pycode}

\foreach \n in {1,2,...,20}{ 
The greatest common divisor of $\py{c}$ and $\py{d}$ is 

\hfill $\gcd\left( \py{c};\py{d} \right) = \py{p}$ 

}

\end{document}

edit : Thanks to @user187803, the number of iterations is now ok, but I am always getting the same example.

2
  • Welcome to TeX.SE :) 1,2,,..,20 should probably be 1,2,...,20. Also, you only draw random numbers for c and d once, so you cannot expect to get 20 different results.
    – user263192
    Commented May 2, 2022 at 18:56
  • @user187803 Thank you ! But how to run the same code several times inside the foreach loop ?
    – RajM
    Commented May 2, 2022 at 19:01

1 Answer 1

0

To get 20 iterations, you have to replace 1,2,,..,20 with 1,2,...,20. You already did that in your edit.

You only draw random numbers for c and d once, so you cannot expect to get 20 different results. You need to draw new values in every iteration, e.g.

\documentclass[12pt]{article}
\usepackage{amsmath, pgffor}
\usepackage{pythontex}
\pagestyle{empty}
\begin{document}
\begin{pycode}
import random 

def gcd(a,b):
   if(b==0):
      return a
   else:
      return gcd(b,a%b)

def next():
    c = random.randint(400,1000)
    d = random.randint(50,400)
    p = gcd(c,d)
    return c, d, p
\end{pycode}

\foreach \n in {1,2,...,20}{ 
\pyc{c, d, p = next()}
The greatest common divisor of $\py{c}$ and $\py{d}$ is 

\hfill $\gcd\left( \py{c};\py{d} \right) = \py{p}$ 

}

\end{document}

enter image description here

3
  • Thank you so much ! I cannot upvote your answer :(
    – RajM
    Commented May 2, 2022 at 19:10
  • You're welcome. But you can accept it ;) Maybe you can upvote later if you like.
    – user263192
    Commented May 2, 2022 at 19:13
  • done. Thank you Boss
    – RajM
    Commented May 2, 2022 at 19:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .