How To Do Math in Python

Síguenos / Follow us!
Facebooktwitterlinkedinrssyoutubeinstagram

Elementary Maths

Divisors

user@pc:~$ python
Python 3.8.6 (default, May 27 2021, 13:28:02) 
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import divisors # We need to import the SymPy library
>>> print(divisors(24)) # Return all divisors of n: [1, 2, 3, 4, 6, 8, 12, 24]
>>> print(divisors(124)) # [1, 2, 4, 31, 62, 124]

Primes

user@pc:~$ python
Python 3.8.6 (default, May 27 2021, 13:28:02)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import primerange, prime, isprime # We need to import the primerange, prime, and isprime functions from the SymPy library
>>> print(list(primerange(0, 36))) # Return all prime numbers in the range [0, 36): [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]

1 is not a prime number. A prime number is a positive integer that has exactly two positive divisors. However, 1 only has one positive divisor (1 itself), so it is not prime.

>>> prime(5) # prime(n) return the nth prime, with the primes indexed as prime(1) = 2, prime(2) = 3, etc., prime(5) = 11
>>> isprime(17) # isprime tests if n is prime, isprime(17) = True, isprime(32) = False

user@pc:~$ python
Python 3.8.6 (default, May 27 2021, 13:28:02)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from sympy import factorint, pprint
>>> pprint(factorint(420, visual=True))
22 ⋅3 1⋅5 1⋅7 1
>>> pprint(factorint(180, visual=True))
22 ⋅3 2⋅5 1

Greatest common divisor (gcd) and least common multiple (lcm)

user@pc:~$ python
Python 3.8.6 (default, May 27 2021, 13:28:02)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.gcd(420, 54)
6
>>> 420*54/6 # lcm(420, 54) = 420*54/math.gcd(420, 54)

Powers and roots

user@pc:~$ python
Python 3.8.6 (default, May 27 2021, 13:28:02)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.sqrt(49) # sqrt() function returns the square root of any number.
7
>>> pow(4, 3) # pow() returns the power of a number.
64
>>> 64**(1/3) # It calculates the cube root of 64
3.9999999999999996

Roman numeric system

Python 3.8.6 (default, May 27 2021, 13:28:02)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import roman # Small helper library to convert arabic to roman numerals.
>>> print(roman.toRoman(124)) # It converts Arabic numbers to Roman Numerals.
CXXIV
>>> print(roman.toRoman(87)) # It converts Arabic numbers to Roman Numerals.
LXXXVII
>>> print(roman.fromRoman("MML")) # It converts Roman Numerals to Arabic numbers.
2050
>>> print(roman.fromRoman("XCVIII")) # It converts Roman Numerals to Arabic numbers.
98

Other number systems: binary, octal, and hexadecimal

user@pc:~$ python
Python 3.8.6 (default, May 27 2021, 13:28:02)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print(bin(79)) # It converts from decimal to binary. The prefix 0b indicates that the value is in binary.
0b1001111
>>> print(oct(79)) # It converts from decimal to octal. The prefix 0o indicates that the value is in octal.
0o117
>>> print(hex(79)) # It converts from decimal to hexadecimal. The prefix 0x indicates that the value is in hexadecimal.
0x4f
>>> print(int("0b1001111", 2)) # It converts from binary to decimal.
79
>>> print(int("0o117", 8)) # It converts from octal to decimal.
79
>>> print(int("0x4f", 16)) # It converts from hexadecimal to decimal.
79

Integers

user@pc:~$ python
Python 3.8.6 (default, May 27 2021, 13:28:02)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 4-5
-1
>>> -5*(-4)
20
>>> (-8)/(-4)
2.0
>>> (-4*7)-(-3*(-2))
-34
>>> abs(-8) # # abs() calculates the absolute value of the number passed as an argument
8

Implementing a Natural class in Python

# It is necessary to overload /
from __future__ import division
import math
import roman
from sympy import divisors, primerange, isprime, factorint, pprint
class myNumber:
    ## Contructs a number
    # @param number, the number itself
    # @param base, the base in which the number is written (default is 10) 
    def __init__(self, number, base = 10):
        if base>= 2 and base<= 36:
            self.number = int(number, base)
        else:
            raise TypeError("The base must be a value between 2 and 36.")
    
    @classmethod     
    def roman(cls, romanNumber):
        return cls(str(roman.fromRoman(romanNumber)))
    
    # Sets need two methods to make an object hashable: __hash__ and __eq__
    def __eq__(self, other):
        return self.number == other.number
    
    # A function hash returns an integer number representing the value of the object     
    def __hash__(self):
        return hash(self.number)
    
    # It is called when print() or str() and returns the string representation of the object
    def __str__(self):
         return str(self.number)
    # It is called when repr() and returns the object representation in string format   
    def __repr__(self):
         return str(self.number)
     
    def __add__(self, other):
        return myNumber(str(self.number + other.number))
    def __sub__(self, other):
        return myNumber(str(self.number - other.number))
    def __mul__(self, other):
        return myNumber(str(self.number * other.number))
    def __truediv__(self, other):
        return myNumber(str(self.number // other.number))  
    def __mod__(self, other):
        return myNumber(str(self.number % other.number))  
    # Return all divisors of our number 
    def divisors(self):
         print("divisors(" + str(self.number)  + ") = ", divisors(self.number))
    # It generates a list of all prime number in the range [0, number).
    def primes(self):
        return list(primerange(0, self.number) )
    # It checks if the number is prime
    def isPrime(self):
        if isprime(self.number):
            print(self.number, "is prime.")
        else:
            print(self.number, "is not prime.")
    # It returns the factorization of the number
    def factorization(self):
        pprint(factorint(self.number, visual=True))
    # It returns the gcd of itself and other.number
    def gcd(self, other):
        print("gcd(" + str(self.number) + ", "  + str(other.number) +  ") =", math.gcd(self.number, other.number))
    # It returns the lcm of itself and other.number
    def lcm(self, other):
        lcmResult = abs(self.number * other.number) // math.gcd(self.number, other.number)
        print("lcm(" + str(self.number) + ", " + str(other.number) + ") =", lcmResult)
    # It returns the square root of the number
    def sqrt(self):
        print("sqrt(" + str(self.number) + ") =", math.sqrt(self.number))      
    def toRoman(self):
        print(str(self.number) + " =", roman.toRoman(self.number))
    def toBinary(self):
        print(str(self.number) + "=" + str(bin(self.number)[2:]) + "\u2082")
    def toOctal(self):
        print(str(self.number) + "=" + str(oct(self.number)[2:]) + "\u2088")
    def toHexadecimal(self):
        print(str(self.number) + "=" + str(hex(self.number)[2:]) + "\u2081\u2086") 
    def abs(self):
        print("|" + str(self.number) + "| = " +  str(abs(self.number)) )
    def fact(self):
        print(str(self.number) + "! = " +  str(math.factorial(self.number)) )

def elementaryMaths():
    myFirstNumber = myNumber("24") 
    myFirstNumber.divisors() # divisors(24) =  [1, 2, 3, 4, 6, 8, 12, 24]
    print(myFirstNumber.primes()) # [2, 3, 5, 7, 11, 13, 17, 19, 23]
    myFirstNumber.isPrime() # 24 is not prime.
    myFirstNumber.factorization() # 23*31
    mySecondNumber = myNumber("4200")
    mySecondNumber.factorization() # 23*31*52*71
    myNumber("60").gcd(myNumber("48")) # gcd(60, 48) = 12
    myNumber("60").lcm(myNumber("48")) # lcm(60, 48) = 240
    myNumber("16").sqrt() # sqrt(16) = 4.0
    mySecondNumber.toRoman() # 4200 = MMMMCC
    myNumber("18").toBinary() # 18=10010₂
    myNumber("19").toOctal() # 19=23₈
    myNumber("19").toHexadecimal() # 19=13₁₆
    myNumber("-19").abs() # |-19| = 19
    myThirdNumber = myNumber.roman("XCVIII") 
    print(myThirdNumber) # 98
    print(myNumber("4F", 16)) # 79
    print(myNumber("7").fact()) # 7! = 5040
    print(myNumber.roman("XVIII") + myNumber("1F", 16)) # 49(=18+31)
    print(myNumber("1F", 16) - myNumber.roman("XVIII")) # 13(=31-18)
    print(myNumber("1F", 16) * myNumber.roman("XVIII")) # 558(=31*18)
    print(myNumber("1F", 16) / myNumber.roman("XVIII")) # 1(=31/18)
    print(myNumber("1F", 16) % myNumber.roman("XVIII")) # 13(=31%18)
if __name__ == '__main__':
    elementaryMaths()
Compártelo / Share it!
Facebooktwitterredditpinterestlinkedinmail

Author: Anawim

I am a social activist. I have two Bachelor's degrees, Maths and Computer & Software Engineering. I also have a Ph.D. in Psychology. I have written nine published books, four scientific articles, and five scientific presentations. I simply want to contribute to making a difference where it counts, so that we make the world a better, more sustainable, prosperous, and fairer place. I am always willing to give free talks and lectures about the social problems that exist in our world today.

Leave a Reply

Your email address will not be published. Required fields are marked *