Table of Contents
show
Program: Finding Square Root of a number using Newtons method
#to find Square root of a number
def SquareRoot(n,d):
x=n/2
count = 0
while(1):
count=count+1
root = 0.5 *(x+(n/x))
if(abs(root-x) < d):
break
x=root
return root
n=int(input("Enter a number"))
d = 0.00001
print("square root of a number =",SquareRoot(n,d))
Output
Enter a number5
square root of a number = 2.23606797749979
Program: Finding GCD
def compute_gcd(x,y):
if x>y:
SmallNum=y
else:
SmallNum=x
for i in range(1,SmallNum+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd
num1=int(input("Enter number1:"))
num2=int(input("Enter number2:"))
print("The GCD of two numbers is :",compute_gcd(num1,num2))
Output,
Enter number1: 4
Enter number2: 8
The GCD of two numbers is : 4
Program to find exponent of a number
def compute_power(b,e):
power = 1
for i in range(1,e+1):
power = power * b
return power
base =int(input("Enter a number:"))
exponent = int(input("Enter exponent:"))
result = compute_power(base,exponent)
print("The result of {0} power {1} = {2}".format(base,exponent,result))
Output,
Enter a number: 2
Enter exponent:3
The result of 2 power 3 = 8
Program to find sum of elements in array
import array
sum = 0
list1=[]
n=int(input("Enter number of elements"))
print("Enter Elements:")
for i in range(0,n):
x=int(input())
list1.append(x)
a = array.array('i',list1)
for i in a:
sum = sum + i
print("Sum = ",sum)
Output
Enter number of elements 3
Enter Elements:
2
1
4
Sum = 7
Program to search an element using Linear Search
import array
def linearsearch(a,n,x):
for i in range(0,n):
if(a[i] == x):
return i
return -1
list1=[]
n=int(input("Enter number of elements"))
print("Enter Elements:")
for i in range(0,n):
x=int(input())
list1.append(x)
a = array.array('i',list1)
item =int(input("Enter elements to search"))
result = linearsearch(a,n,item)
if(result == -1):
print("Element not found")
else:
print("Element found at index:",result)
Output,
Enter number of elements 5
Enter Elements:
3
2
5
1
9
Enter elements to search 1
Element found at index: 3
Program to search an element using Binary Search
import array
def binarysearch(a,n,item):
low = 0
high= n-1
while low <= high:
mid = ((low + high) // 2)
if item == a[mid]:
return mid
elif item > a[mid]:
low = mid + 1
else:
high = mid - 1
return -1
list1=[]
n=int(input("Enter number of elements"))
print("Enter Elements in sorted order:")
for i in range(0,n):
x=int(input())
list1.append(x)
a = array.array('i',list1)
item =int(input("Enter elements to search"))
result = binarysearch(a,n,item)
if(result == -1):
print("Element not found")
else:
print("Element found at index:",result)
Output,
Enter number of elements 5
Enter Elements in sorted order:
10
20
30
40
50
Enter elements to search 10
Element found at index: 0
Views: 0