Strategies for debugging:

-Print out intermediate information (eg print statements)

-Commenting your code

-Naming variables descriptively

-Testing early - try to break things

-Modularity - breaking up code into pieces that can be tested separately (eg make lots of different functions) -First solve an easier case

-Explain your code to someone else

-"Rubber ducky" debugging

In [ ]:
# CHALLENGE: find gcd(24,36) using Euclidean algorithm, by hand on paper
In [2]:
# CHALLENGE: write my_gcd (Hint: use recursion)
def my_gcd(a,b):
    """Return gcd(a,b), computed using Euclidean algorithm.
        a,b non-negative integers"""
    if a<b:
        a,b = b,a # swaps a,b if a<b
    # Now we can assume that a>=b
    if b==0:
        return a 
    return my_gcd(a%b,b) # recursive call
    
In [3]:
my_gcd(39,24)
Out[3]:
3
In [4]:
my_gcd(24,36)
Out[4]:
12
In [5]:
my_gcd(24,0)
Out[5]:
24
In [6]:
my_gcd(24,1)
Out[6]:
1
In [11]:
my_gcd(21391201292181, 12323123123928)
Out[11]:
3
In [12]:
my_gcd(2^123, 2^135)
Out[12]:
10633823966279326983230456482242756608
In [14]:
my_gcd(2^123, 2^135 - 1)
Out[14]:
1
In [21]:
%%time
my_gcd(10^12349999, 10^12329999- 3^45)
CPU times: user 1.3 s, sys: 31 ms, total: 1.33 s
Wall time: 1.33 s
Out[21]:
1
In [ ]:
# upshot: my_gcd is very fast
# we will now compare to factoring (which gives another way of finding gcd)
In [22]:
# bultin factor function. Can find gcd(24,36) using prime factorization, as below
factor(24), factor(36)
Out[22]:
(2^3 * 3, 2^2 * 3^2)
In [24]:
%%time
factor(2^123), factor(2^135 - 1)
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 1.18 ms
Out[24]:
(2^123,
 7 * 31 * 73 * 151 * 271 * 631 * 23311 * 262657 * 348031 * 49971617830801)
In [26]:
factor(2^235)
Out[26]:
2^235
In [32]:
%%time
factor(2^335-1)
CPU times: user 828 ms, sys: 0 ns, total: 828 ms
Wall time: 852 ms
Out[32]:
31 * 464311 * 193707721 * 1532217641 * 761838257287 * 21505409328405921060057783156144213618485460844911284448661782641
In [ ]:
# amount of time factor(n) takes is very roughly around n 
# amount of time gcd(n,m) is around the number of digits of n or m