0% found this document useful (0 votes)
13 views37 pages

Pthon Module 4

Unit 4 of CSE1021 covers various factoring methods in Python, including finding square roots, smallest divisors, GCD, generating prime numbers, and computing prime factors. It provides detailed explanations and code examples for each method, demonstrating how to implement them using Python's built-in functions and modules. Additionally, it discusses generating pseudo-random numbers with various functions from the random module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views37 pages

Pthon Module 4

Unit 4 of CSE1021 covers various factoring methods in Python, including finding square roots, smallest divisors, GCD, generating prime numbers, and computing prime factors. It provides detailed explanations and code examples for each method, demonstrating how to implement them using Python's built-in functions and modules. Additionally, it discusses generating pseudo-random numbers with various functions from the random module.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

CSE1021

Introduction to Problem Solving and Programming

School of Computing Science and Engineering


VIT Bhopal University

Unit 4 Factoring Methods / 1


Unit IV: Factoring Methods
Finding square root – Smallest Divisor – GCD – Generate Prime
Numbers – Computing Prime Factors – Generating
Pseudo-random numbers – Raising a Number to Large Power –
Computing nth Fibonacci Numbers.

Unit 4 Factoring Methods / 2


Finding square root
How to write square root in Python?
• Python has a predefined sqrt() function that returns the square root of a number.
• It defines the square root of a value that multiplies itself to give a number.
• The sqrt() function is not used directly to find the square root of a given number, so we
need to use a math module to call the sqrt() function in Python.

Using math.sqrt() method


• The sqrt() function is an inbuilt function that returns the square root of any number.
Following are the steps to find the square root of a number.
1. Start the program
2. Define any number whose square root to be found.
3. Invoke the sqrt() function and pass the value that you have defined in step 2 and
store the result in a variable.
4. Print the square root.
5. Terminate the program.

Unit 4 Factoring Methods / 3


Finding square root
import math # import math module
N = 25 # define the value to the variable N
result = math.sqrt(N) # use math.sqrt() function and pass the variable.
print(" Square root of 25 is :", result) # prints the square root of a given number

M = 625 # define the value


result = math.sqrt(M) # use math.sqrt() function and pass the variable
print(" Square root of 625 is :", result) # prints the square root of a given number

P = 144 # define the value


result = math.sqrt(P) # use math.sqrt() function and pass the variable
print(" Square root of 144 is :", result) # prints the square root of a given number

S = 64 # define the value


result = math.sqrt(S) # use math.sqrt() function and pass the variable
print(" Square root of 64 is :", result) # prints the square root of a given number
Unit 4 Factoring Methods / 4
Finding square root
Let's create a python program that finds the square root of a decimal numbers.

import math
print(" The Square root of 4.5 is", math.sqrt(4.5)) # Pass the decimal number
print(" The Square root of 627 is", math.sqrt(627)) # Pass the decimal number
print(" The Square root of 6.25 is", math.sqrt(6.25)) # Pass the decimal number

print(" The Square root of 0 is", math.sqrt(0)) # Pass number as 0


eg- num=36
while (i<=num/2)
{
if (num/i==i)
{
…….
i++;
}
Unit 4 Factoring Methods / 5
Finding square root
In the following program, we have read a number form the user and find the square root.

import math # import math module


a = int(input("Enter a number to get the Square root")) # take an input
res = math.sqrt(a) # Use math.sqrt() function and pass the variable a.
print("Square root of the number is", res) # print the Square Root

Unit 4 Factoring Methods / 6


Finding square root
Using math.pow() function
The pow() is an inbuilt function that is used in Python to return the power of a number. It
has two parameters. The first parameter defines the number and second parameter defines
the power raise to that number.

import math # import the math module


num = float(input("Enter the number :")) # take an input
SquareRoot = math.pow(num, 0.5)
# Use the math.pow() function and pass the value and 0.5 (which is equal to √) as an parameters
print(" The Square Root of the given number {0} = {1}" .format(num, SquareRoot))
# print the Square Root.

Unit 4 Factoring Methods / 7


Finding square root
Using ** Operator
We can also use the exponent operator to find the square root of the number. The operator
can be applied between two operands. For example, x**y. It means that left operand raised
to the power of right.

Following are the steps to find the square root of a number.


Step 1. Define a function and pass the value as an argument.
Step 2. If the defined number is less than 0 or negative, it returns nothing.
Step 3. Use the exponential ** sign to find the power of a number.
Step 4. Take the numeric value from the user.
Step 5. Call the function and store its output to a variable.
Step 6. Display the Square Root of a number in Python.
Step 7. Exit from the program.

Unit 4 Factoring Methods / 8


Finding square root
import math # import the math package or module
def sqrt_fun(num): # define the sqrt_fun() and pass the num as an argument
if num < 0: # if num is less than 0 or negative, it returns nothing
return
else:
return num ** 0.5 # Use the exponent operator
num = int(input (" Enter a numeric value: ") ) # take an input from the user
res = sqrt_fun(num) # call the sqrt_fun() to find the result
print(" Square Root of the {0} = {1}".format(num, res))
# print the Square Root of the variable

Unit 4 Factoring Methods / 9


Smallest Divisor
• The number ‘y’ is called the divisor of a number ‘x’ if ‘x/y’ is 0. Our program
will ask the user to enter a no.
• It will then find out the lowest divisor of that number.

• If the number is 10, then its divisors are 1,2,5 and 10. We will ignore 1 and
consider 2 as the smallest divisor for the number.
eg- num=15
num = int(input("Enter a number : ")) i=2
while (i<=num/2)
for i in range(2, num+1):
if num % i == 0: {
print ("The smallest divisor for {} is {}".format(num, i))
if (num % i==0)
break
{
Enter a number : 13
The smallest divisor for 13 is 13 print (i)
Enter a number : 14
i+1;
The smallest divisor for 14 is 2
Unit 4 Factoring Methods / 10
}
Smallest Divisor
1. Take in an integer from the user.
2. Use a for loop where the value of i ranges from 2 to the integer.
3. If the number is divisible by i, the value of i is appended to the list.
4. The list is then sorted and the smallest element is printed.
5. Exit.

n=int(input("Enter an integer:")) Case 1:


a=[] Enter an integer:75
for i in range(2,n+1): Smallest divisor is: 3
if(n%i==0):
a.append(i) Case 2:
a.sort() Enter an integer:64
print("Smallest divisor is:",a[0])
Smallest divisor is: 2
Unit 4 Factoring Methods / 11
GCD of two numbers
(Greatest Common Divisor)
# Python code to demonstrate the working of gcd()
# importing "math" for mathematical operations
import math
print("The gcd of 60 and 48 is : ", end="")
print(math.gcd(60, 48))

Output
The gcd of 60 and 48 is : 12

Unit 4 Factoring Methods / 12


GCD of two numbers
(Greatest Common Divisor)
# Python code to demonstrate naive
# method to compute gcd ( recursion ) eg- num 1=12, num 2 =30

while (min >=2)


def hcf(a, b): Output
if(b == 0): The gcd of 60 and 48 is : 12 {
return a
if (num1 % min==0)&&(num2 % min==0)
else:
return hcf(b, a % b) {
a = 60
print (min)
b = 48 }
print("The gcd of 60 and 48 is : ", end="")
min --;
print(hcf(60, 48))
}

Unit 4 Factoring Methods / 13


GCD of two numbers
(Greatest Common Divisor)
# Recursive function to return gcd of a and b
def gcd(a,b): # Driver program to test above function
if(b==0): a = 98
return a b = 56
else: if(gcd(a, b)):
return gcd(b,a%b) print('GCD of', a, 'and', b, 'is', gcd(a, b))
a=int(input("Enter first else:
number:")) print('not found')
b=int(input("Enter second
number:"))
Output
GCD=gcd(a,b)
print("GCD is: ") GCD of 98 and 56 is 14
print(GCD)

Unit 4 Factoring Methods / 14


Generate Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors
other than 1 and itself.
For example: 2, 3, 5, 7, 11

Composite number:
Other natural numbers that are not prime numbers are called composite numbers.
For example: 4, 6, 9 etc. are composite numbers.

Unit 4 Factoring Methods / 15


Enter an input number:17 17 is a prime number
Generate Prime Numbers
# A default function for Prime checking conditions

a=int(input("Enter number: "))


k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
Enter an input number: 17
print("Number is prime") 17 is a prime number
else:
print("Number isn't prime")

Unit 4 Factoring Methods / 16


Generate Prime Numbers

A prime number is a natural number greater than 1 that has no positive divisors
other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ….}.

# Python program to print all prime number in an interval number should be greater than 1
start = 11
end = 25
for i in range(start, end+1): Output:
if i > 1: 11
for j in range(2, i): 13
if(i % j == 0): 17
break 19
else: 23
print(i)

Unit 4 Factoring Methods / 17


Generate Prime Numbers

#Take the input from the user:


def check(n, div = None):
if div is None:
div = n - 1
while div >= 2:
if n % div == 0:
print("Number not prime")
return False
else:
return check(n, div-1)
else:
print("Number is prime")
return 'True'
n=int(input("Enter number: "))
check(n)
Unit 4 Factoring Methods / 18
Computing Prime Factors

If the user enters the number as 12, then the output must be '2, 2, 3, and if the
input is 315; the output should be "3 3 5 7".

The program must return the prime all prime factor of given number.

The prime factors of 330 are 2, 3, 5, and 11.

Therefore 11 is the most significant prime factor of 330.

For Example: 330 = 2 × 3 × 5 × 11.

Unit 4 Factoring Methods / 19


Computing Prime Factors
Steps to find all prime factors.
1) While n is divisible by 2, print 2 and divide n by 2.
2) After step 1, n must be odd. Now start a loop from i = 3
to the square root of n. While i divides n, print i, and divide
n by i. After i fails to divide n, increment i by 2 and
continue.
3) If n is a prime number and is greater than 2, then n will
not become 1 by the above two steps. So print n if it is
greater than 2.

Unit 4 Factoring Methods / 20


Computing Prime Factors

n=int(input("Enter an integer:"))
print("Factors are:")
i=1
while(i<=n):
k=0 Output:
if(n%i==0): 2
j=1 2
while(j<=i): 2
if(i%j==0): 5
k=k+1 5
j=j+1
if(k==2):
print(i)
i=i+1
Unit 4 Factoring Methods / 21
Generating Pseudo-random numbers
Function What it does
randint(x, y) Generates a random integer from x to y, including the x and y.

randrange(start, stop, step) Generates a random integer in the range(start, stop, step)
random() Generates a random floating-point number in the interval [0,1)

uniform(x, y) It generates a floating-point value between x and y.

Selects k unique random elements from a population sequence


sample(population, k)
or set.

choice(seq) Chooses a random element from a non-empty sequence seq.


shuffle(x) Shuffles list x in place.
Generates the same sequence of random numbers every time
seed(x)
you call seed(x).
Unit 4 Factoring Methods / 22
Generating Pseudo-random numbers

1. Python randint()
This function generates an integer between the specified limits. It takes two
arguments x and y and produces integer i such that x <= i <= y.

>>> import random


>>> random.randint(3, 5)

Output:
4

Unit 4 Factoring Methods / 23


Generating Pseudo-random numbers

2. Python randrange()
This function takes 2 arguments start and stop along with 1 optional argument step. And
returns a random integer in the range(start, stop, step). The default value of step is 1.

>>> import random


>>> random.randrange(1, 10, 2)

Output:
3

In this example, the output will be a random integer from [1, 3, 5, 7, 9] as the start and
stop values are 1 and 10 respectively and the step value is 2.

Unit 4 Factoring Methods / 24


Generating Pseudo-random numbers
3. Python random()
This function returns a random floating-point number between 0 and 1 (excluding 0 and 1).
>>> import random
>>> random.random()
Output:
0.5313843048739985

4. Python uniform()
This function lets you generate a floating-point number within a specific limit. It takes two
arguments to start and stop and then returns a float between the start and stop (including
the limits).
>>> import random
>>> random.uniform(6, 9)

Output:
6.338126781525701
Unit 4 Factoring Methods / 25
Generating Pseudo-random numbers
5. Python choice()
If you want to choose a random element from a specific sequence, you can use this
function. It takes one argument – the sequence. And it returns a random element from the
sequence.
>>> import random
>>> seq = (12, 33, 67, 55, 78, 90, 34, 67, 88)
>>> random.choice(seq)

Output:
67

Unit 4 Factoring Methods / 26


Generating Pseudo-random numbers
6. Python sample()
If you want more than one random element from a sequence, you can use sample(). It takes
two arguments population and k, where population is a sequence and k is an integer. Then
it returns a list of k random elements from the sequence population.

>>> import random


>>> seq = (12, 33, 67, 55, 78, 90, 34, 67, 88)
>>> random.sample(seq, 5)

Output:
[33, 90, 78, 88, 12]

Unit 4 Factoring Methods / 27


Generating Pseudo-random numbers
7. Python shuffle()
This function takes one argument – a list. It then shuffles the elements of the list in place
and returns None.
>>> import random
>>> l = [10, 20, 30, 40, 50]
>>> random.shuffle(l)
>>> print(l)

Output:
[20, 40, 30, 50, 10]

Ref:
https://techvidvan.com/tutorials/python-random-number-generator/

Unit 4 Factoring Methods / 28


Generating Pseudo-random numbers
8. Python seed()
You can use this function when you need to generate the same sequence of random
numbers multiple times. It takes one argument- the seed value. This value initializes a
pseudo-random number generator. Now, whenever you call the seed() function with this
seed value, it will produce the exact same sequence of random numbers.
# seed value again = 3
import random random.seed(3)
# seed value = 3 for i in range(3):
random.seed(3) print(random.random(), end = ' ')
for i in range(3): print('\n')
print(random.random(), end = ' ')
Output:
print('\n') 0.23796462709189137 0.5442292252959519
# seed value = 8 0.369955166548079250.2267058593810488
random.seed(8) 0.9622950358343828 0.12633089865085956
for i in range(3): 0.23796462709189137 0.5442292252959519
0.36995516654807925
print(random.random(), end = ' ')
print('\n‘) Unit 4 Factoring Methods / 29
Raising a Number to Large Power
Exponentiation in Python with **
# Input value
valueA = 3
valueB = 144
# Calculate the exponent for the variables
A Exp = valueA ** 2
B Exp = valueB ** 3

# Output the results


print(valueA, "^2 = ", aExp, sep="")
print(valueB, "^3 = ", bExp, sep="")

Unit 4 Factoring Methods / 30


Raising a Number to Large Power
Exponents with the pow() function

Another way to exponentiate values is with the built-in pow() function (Python.org, n.d. a).
This function accepts two arguments.
The first is the base, or the number that we want to raise to a particular power. The second
is the exponent to use. pow() always calculates an exact integer power.

So to calculate 32, we use the pow() function like this:

pow(3, 2) # Returns: 9

Unit 4 Factoring Methods / 31


Raising a Number to Large Power
Raise numbers to a power with pow()

# Some random values


valueA = 3
valueB = 144
# Raise the variables to different powers
aExp = pow(valueA, 2)
bExp = pow(valueB, 3)

# Output results Output:


print(valueA, "^2 = ", aExp, sep="") 3^2 = 9
print(valueB, "^3 = ", bExp, sep="") 144^3 = 2985984

Unit 4 Factoring Methods / 32


Raising a Number to Large Power
Raise numbers to a power with Python’s math.pow()

A quick example of math.pow() is:


import math
math.pow(3, 2) # Returns: 9.0

Unit 4 Factoring Methods / 33


Raising a Number to Large Power
Raise numbers to a power with Python’s math.pow()
import math
# Some numerical values
valueA = 3
valueB = 144
valueC = -987

# Raise each variable to a certain power


aExp = math.pow(valueA, 2) Output:
bExp = math.pow(valueB, 3) 3^2 = 9.0
cExp = math.pow(valueC, 4) 144^3 = 2985984.
0 -987^4 = 949005240561.0
# Output the results
print(valueA, "^2 = ", aExp, sep="")
print(valueB, "^3 = ", bExp, sep="")
print(valueC, "^4 = ", cExp, sep="")

Unit 4 Factoring Methods / 34


Computing nth Fibonacci Numbers
A Fibonacci number can be defined as such, where the next number is the sum of the
previous two numbers.
The first two terms of the series are 0 and 1. The third term can be calculated by adding the
previous terms, hence the third term is 1 (0 + 1). The fourth term will be the sum of the
second and third terms which is 2 (1 + 1). The series of such numbers is called a Fibonacci
series.
A Fibonacci number is defined by the recurrence relation:
Fn = Fn-1 + Fn-2

The first few numbers in the series are:


0,1,1,2,3,5,8,13,21........

To compute nth Fibonacci number, we can follow two approaches:


1. Using recursion
2. Using list

Unit 4 Factoring Methods / 35


Computing nth Fibonacci Numbers

Suppose we have a number n. We have to find the nth Fibonacci


term by defining a recursive function.
# Function for nth Fibonacci number
So, if the input is like n = 8, then the output will be 13 as first def solve(n):
few Fibonacci terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... if n <= 2:
To solve this, we will follow these steps − return n - 1
else:
Define a function solve() . This will take n return solve(n - 1) + solve(n - 2)
if n <= 2, then
return n - 1
otherwise, n=8
return solve(n - 1) + solve(n - 2) print(solve(n))

Unit 4 Factoring Methods / 36


Computing nth Fibonacci Numbers
Dynamic Programming Method Step 1- Define a function fib_number() that will calculate nth Fibonacci number

#list Step 2- Check if the number is less than or equal to zero or not

def fib_number(n): Step 3- If true print "cant be computed"


if n<= 0:
return "incorrect, can't be computed" Step 4- Else declare a list fib=[0,1] where 0 and 1 are the first two terms
else: Step 5- if n is greater than 2, run a loop from 2 to the number
fib = [0, 1] Step 6- use append () to add the value of the next Fibonacci number in the list fib
if n > 2: Step 7- the next term(n) will be calculated as the sum of the (n-1)th term
for i in range (2, n): and (n-2)th term

fib.append(fib[i-1] + fib[i-2]) Step 8- return the value of the nth term from the list
return fib[n-1] Step 9- Take input of the value n from the user

Step 10- pass the input as parameter in the function fib_number()


#input
n=int(input("Enter n: "))
Output
print("{}th fibonacci number is: ".format(n),fib_number(n)) 13

Unit 4 Factoring Methods / 37

You might also like