Thursday, 15 January 2015

Iterative Algorithms

Example 1

# This code squares the value of x by repetitive addition

# Initializing the variables
x = 7
ans = 0
iterLeft = x

# Iterate through the loop x number of times
while (iterLeft != 0):
    ans = ans + x
    iterLeft = iterLeft - 1

# Print the result of the number that is squared
print(str(x) + ' * ' + str(x) + ' = ' + str(ans))


Example 2

 

#Defining gcdIter function
def gcdIter(a, b):

     small_num = min(a, b)
     while ( (a % small_num != 0) or (b % small_num != 0) ):
         small_num = small_num - 1
     return small_num

# Initializing variables
num1 = int(raw_input('Enter the first number: '))
num2 = int(raw_input('Enter the second number: '))

# Calling gcdIter function
gcd_result = gcdIter(num1, num2)

#Printing results
print '\nThe greatest common divisor of ' + str(num1) + ' and ' + str(num2) + ' is ' + str(gcd_result)

Example 3


# To find Cube root of an integer


#Initializing variables
x = int(raw_input('Enter an integer: '))
ans = 0

# Iterate through loop
while ans**3 < x:
     ans = ans + 1

#Check the answer
if ans**3 != x:
     print('\n' + str(x) + ' is not a perfect cube')
else:
     print('\n Cube root of ' + str(x) + ' is ' + str(ans))



 Example 5


#Decimal to Binary conversion



#Initializing the variables
num = 8
result = ''
ifNeg = 0

#To check whether number is Negative or positive
if num < 0:
isNeg = True
num = abs(num)
else:
isNeg = False
#To handle if num is '0'
if num == 0:
result = 0

#Converting decimal number into binary number

#Storing number in result
while num > 0:
result = str(num % 2 ) + result
num = num / 2

#To handle negative number
if isNeg:
result = '-' + result
#Printing result
print result





 Example 6



# Defining function iterMulti

def iterMulti(m, n):
result = 0
    while (n !=0):
         result += m
         n -= 1
    return result

#Initializing variables
m = 90
n = 5

#Calling the function 'iterMulti'
result = iterMulti(m, n)

#Printing the result
print 'The result using iterative Multiplication is: ' + str(result)