Showing posts with label Math. Show all posts
Showing posts with label Math. Show all posts

Volume and Surface area of Hemisphere

import math

def volume(r):

volume = 2 * math.pi * math.pow(r, 3) / 3

print("Volume = ", '%.4f' %volume)

def surface_area(r):

s_area = 2 * math.pi * math.pow(r, 2)

print("Surface Area = ", '%.4f' %s_area)

r = 11

volume(r)

surface_area(r)


Dyck path

def countDyckPaths(n):

res = 1

for i in range(0, n):

res *= (2 * n - i)

res /= (i + 1)

return res / (n+1)

n = 4

print("Number of Dyck Paths is ",

str(int(countDyckPaths(n))))


Optimum location of point to minimize total distance

import math

class Optimum_distance:

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

class Line:

def __init__(self, a, b, c):

self.a = a

self.b = b

self.c = c

def dist(self, x, y, p):

return math.sqrt((x - p.x) ** 2 +

(y - p.y) ** 2)

def compute(self, p, n, l, x):

res = 0

y = -1 * (l.a*x + l.c) / l.b

for i in range(n):

res += self.dist(x, y, p[i])

return res

def find_Optimum_cost_untill(self, p, n, l):

low = -1e6

high = 1e6

eps = 1e-6 + 1

while((high - low) > eps):

mid1 = low + (high - low) / 3

mid2 = high - (high - low) / 3

dist1 = self.compute(p, n, l, mid1)

dist2 = self.compute(p, n, l, mid2)

if (dist1 < dist2):

high = mid2

else:

low = mid1

return self.compute(p, n, l, (low + high) / 2)

def find_Optimum_cost(self, p, l):

n = len(p)

p_arr = [None] * n

for i in range(n):

p_obj = self.Point(p[i][0], p[i][1])

p_arr[i] = p_obj

return self.find_Optimum_cost_untill(p_arr, n, l)

if __name__ == "__main__":

obj = Optimum_distance()

l = obj.Line(1, -1, -3)

p = [ [ -3, -2 ], [ -1, 0 ],

[ -1, 2 ], [ 1, 2 ],

[ 3, 4 ] ]

print(obj.find_Optimum_cost(p, l))


Euler’s Totient function for all numbers smaller than or equal to n

def computeTotient(n):

phi=[]

for i in range(n + 2):

phi.append(0)

for i in range(1, n+1):

phi[i] = i 

for p in range(2,n+1):

if (phi[p] == p):

phi[p] = p-1

for i in range(2*p,n+1,p):

phi[i] = (phi[i]//p) * (p-1)

for i in range(1,n+1):

print("Totient of ", i ," is ",

phi[i])

n = 12

computeTotient(n)


Maximum profit by buying and selling a share at most k times

def maxProfit(prices, n, k):

profit = [[0 for i in range(k + 1)]

for j in range(n)]

for i in range(1, n):

for j in range(1, k + 1):

max_so_far = 0

for l in range(i):

max_so_far = max(max_so_far, prices[i] -

prices[l] + profit[l][j - 1])

profit[i][j] = max(profit[i - 1][j], max_so_far)

return profit[n - 1][k]

k = 2

prices = [10, 22, 5, 75, 65, 80]

n = len(prices)

print("Maximum profit is:",

maxProfit(prices, n, k))


Program for Find sum of even factors of a number

import math

def sumofFactors(n) :

if (n % 2 != 0) :

return 0

res = 1

for i in range(2, (int)(math.sqrt(n)) + 1) :

count = 0

curr_sum = 1

curr_term = 1

while (n % i == 0) :

count= count + 1

n = n // i

if (i == 2 and count == 1) :

curr_sum = 0

curr_term = curr_term * i

curr_sum = curr_sum + curr_term

res = res * curr_sum

if (n >= 2) :

res = res * (1 + n)

return res

n = 18

print(sumofFactors(n))


Program for Legendre\’s Conjecture

import math

def isprime( n ):

i = 2

for i in range (2, int((math.sqrt(n)+1))):

if n%i == 0:

return False

return True

def LegendreConjecture( n ):

print ( "Primes in the range ", n*n

, " and ", (n+1)*(n+1)

, " are:" )

for i in range (n*n, (((n+1)*(n+1))+1)):

if(isprime(i)):

print (i)

n = 50

LegendreConjecture(n)


Finding sum of digits of a number until sum becomes single digit

import math

def digSum( n):

sum = 0

while(n > 0 or sum > 9):

if(n == 0):

n = sum

sum = 0

sum += n % 10

n /= 10

return sum

n = 1234

print (digSum(n))


Program for Product of unique prime factors of a number

import math

def productPrimeFactors(n):

product = 1

if (n % 2 == 0):

product *= 2

while (n%2 == 0):

n = n/2

for i in range (3, int(math.sqrt(n)), 2):

if (n % i == 0):

product = product * i

while (n%i == 0):

n = n/i

if (n > 2):

product = product * n

return product

n = 44

print (int(productPrimeFactors(n)))


Legendre's Conjecture program

import math

def isprime( n ):

i = 2

for i in range (2, int((math.sqrt(n)+1))):

if n%i == 0:

return False

return True

def LegendreConjecture( n ):

print ( "Primes in the range ", n*n

, " and ", (n+1)*(n+1)

, " are:" )

for i in range (n*n, (((n+1)*(n+1))+1)):

if(isprime(i)):

print (i)

n = 50

LegendreConjecture(n)



Program to find LCM

def calculate_lcm(x, y):  

    if x > y:  

        greater = x  

    else:  

        greater = y  

    while(True):  

        if((greater % x == 0) and (greater % y == 0)):  

            lcm = greater  

            break  

        greater += 1  

    return lcm    

num1 = int(input("Enter first number: "))  

num2 = int(input("Enter second number: "))  

print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2))  


Solving linear mathematical equations with two variable

import numpy as np
A=np.array([[1.5,1],[3.75,4]])
B=np.array([1800,900])
x=np.linalg.solve(A,B)
print("Values of A and B variables:",x)
h=np.allclose(np.dot(A, x), B)
print("Substitution of two variables in equation to validate:",h)

Mathematical operators on Numpy Array and List

import numpy as np

a = np.array([1, 2, 3])
print(type(a))           
print('Numpy Array:\n',a)
print('Addition of Numpy Arrays with constant:\n',a+13)
print('Addition of Numpy Arrays:\n',a+a)
print('Multiplication of Numpy Arrays with constant:\n',a*3)
print('Multiplication of Numpy Arrays with another:\n',a*a)
print('Divison of Numpy Arrays with constant:\n', a/3)
print('Divison of Numpy Arrays with another:\n', a/a)
print('Power of Numpy Arrays with constant:\n', a**4)
print('Power of Numpy Arrays with another:\n', a**a)
print('Remainder of Numpy Arrays with constant:\n',a%2)
print('Remainder of Numpy Arrays with another:\n',a%a)
print('Subtraction of Numpy Arrays with constant:\n', a-1)
print('Subtraction of Numpy Arrays with another:\n', a-a)

try:
  a1=[1, 2, 3]
  print('\n',type(a1))
  print('Common List:\n', a1)
  print('Addition of Lists:\n',a1+a1)
  print('Multiplication of List with constant:\n',a1*3)
  print(a1+13) #error
  print(a1*a1) #error
  print(a1/3) #error
  print(a1/a1) #error
  print(a1**4) #error
  print(a1*a1) #error
  print(a1%2) #error
  print(a1%a1) #error
  print(a1-1) #error
  print(a1-a1) #error
except TypeError:
  print('TypeError')
 

Perimeter and area of a circle and finding Natural Exponential Function

import math
r=int(raw_input('Enter the radius of circle:'))
perimeter=2*math.pi*r
print 'Perimeter of a circle :',perimeter
area=math.pi*(r**2)
print 'Area of acircle :',area

x=int(raw_input('Enter the value of x in y=e**x:'))
y=math.e**x
print 'Natural Exponential Function value :',y

Trigonometric Functions

import math
d=int(raw_input('Enter the angle in degree:'))
x= math.radians(d)
print 'Corresponding Radians is:',x           #Converts angle from degrees to radians.
f1=math.acos(x)                                                          # Return the arc cosine of x
print 'acos',f1
f2=math.asin(x)                                                           #Return the arc sine of x
print 'asin',f2
f3=math.atan(x)                                                          #Return the arc tangent of x
print 'atan',f3
f4=math.cos(x)                                                            #Return the cosine of x
print 'cos',f4
f5=math.sin(x)                                                             #Return the sine of x
print 'sin',f5
f6= math.tan(x)                                                            # Return the tangent of x
print 'tan',f6

u=int(raw_input('Enter the value of x:'))
v=int(raw_input('Enter the value of y:'))
e=math.hypot(u, v)                                                 #Return the Euclidean norm, sqrt(u*u + v*v)
print 'The Euclidean norm:',e