Archive

Posts Tagged ‘Code’

Python: Largest Prime Factor



Python: Largest Prime Factor
Problem No.3 on ProjectEuler

Quite easy one to solve, in this task we need to get all the factors of a given number, then to print out the largest prime one.



To solve this with a Large Number I search the net and i fond an article explain it. So here i am putting it in points.



Factors of Large Numbers:
1. First ask if the number N is (Even or Odd)?
2. If the number N is Even, then factors=(2) then, the new N = N Divide by 2.
3. If the number N is Ood, then start form 3 and get/find smallest prime factors (SPF) of it.
4. Add the smallest prime factors to factors list.
5. Then, the new N = N Divide by smallest prime factors (SPF).
6. If the new N is Even goto line 2, If the new N is Odd goto line 3.





The Code:




# Largest prime factor
# Problem No.3
# Solved

def factors_of_n(num):

a=3

while a <= num:

if num%a==0:

return int(a)

break

a = a + 1


# This is the number from ProjectEuler
num = 600851475143
temp_num = num
facto_back =0
p_factors =[]
the_num=1

while temp_num > 1 :

if temp_num%2==0 :

p_factors.append(2)

temp_num = temp_num / 2

else:

facto_back =factors_of_n(temp_num)

p_factors.append(facto_back)

temp_num = temp_num / facto_back

print(p_factors)
print(‘\n Largest Prime Factor of {} is {}’.format(num,max(p_factors)))




Python Project: Split and join




Python: Split and join


Split up the message on newline

The target of this task is to Split a given text message on the newline (\n) then use the join builtin to stitch it together using a ‘|’ (pipe).

I fond this on the pybites web-site as a code-challenges bites #104. In our case we will print the new Message within the function but we can return it back as a variable for more usage in our code..

Enhancements: If we want to do some enhancements to this code:

1. We can read the message from a file.

2. Letting the user to select the joining character.

3. Also we may export the final message to another txt file.


We assume our message is “Hello world!\nWe hope that you are learning a lot of Python.\nHave fun with our Bites of Py.\nKeep calm and code in Python!\nBecome a PyBites ninja!”



The Code:


def split_in_columns(message=message):

sp_message = message.split(“\n”)

message=”|”.join(sp_message)

print(message)

split_in_columns(message=message)







Follow me on Twitter..

Python: Digit Factorial Chains



Python: Digit factorial Chains
Problem No.74 @ ProjectEuler

In this task, we need to produce a chain of the summation of a factorial number and keep chasing each number in the chain until it starts repeat, we stop there and count the length of the chain, if its 60 then we increase a counter. ProjectEuler task 74 ask to do this and get all the numbers (How many are they?) below one Million (1000000) that has 60 numbers in it’s chain.

So we start to write two functions, one to get the factorial of a number, and the other to get the summation of the numbers in a list. Then with two (while) loop, an outer one to count the 60’s chain numbers, and an inner one to produce the chains.

At the end we manage to solve the problem 74 using Pythonanywhere.



The Code:



#Digit factorial chains
#Problem 74

numbers=[]

# Function to get the Factorials of a number.
def get_factorial(num):

if (num == 0) :

return 1

else:

return num * get_factorial(num-1)

def get_summation(the_list):

tot=0

for each in the_list:

tot +=each

return tot

start_num = 2

the_num = start_num
keep_chain=[start_num]
chain_count = 0

print(‘We start with number ‘,start_num)
the_facto_d_sum = 0

while start_num < 1000000 :

the_num = start_num

keep_chain=[start_num]

while the_facto_d_sum != start_num:

for each in str(the_num):

numbers.append(get_factorial(int(each)))

the_facto_d_sum = get_summation(numbers)

the_num = the_facto_d_sum

if the_num in keep_chain :

the_facto_d_sum = start_num

else:

keep_chain.append(the_num)

numbers=[]

if len(keep_chain) == 60:

chain_count +=1

keep_chain =[]

start_num +=1

print(‘we have {} numbers with 60 ‘.format(chain_count))







Follow me on Twitter..



Python: Distinct Powers



Python: Distinct Powers
ProjectEuler Problem No.29

In this project we have a sequance of numbers based on a powered number, it takes ten minites or less to write the code, test it and applay the needed figures to solve the problem. Thie code can be shorten, but I am using the classic way to write functions with comments on code.

Here is the Problem as on the ProjectEuler Portal:
Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?





The Code:


#Distinct powers
#Problem 29

sequence_list=[]

def get_sequence (a):

for b in range (2,101):

if a**b not in sequence_list:

#If the elements NOT exist in the list then add it.

sequence_list.append(a**b)

for a in range (2,101):

get_sequence (a) # Calling the function

# Get the total elements in the sequence_list
print (len(sequence_list))






Follow me on Twitter..



Python: Perfect Number



Python: Non-abundant sums
Problem No.23 @ ProjectEuler

In projecteuler Problem No. 23 talking about Non-abundant sums to clear this it state three categories for a numbers.

1. A number N called Perfect Number if the sum of its divisors are equal to the number it self. So 28 is a perfect number because the divisors of 28 are 1,2,4,7,14 they equal to 28.
( 1 + 2 + 4 + 7 + 1 4 = 28)

2. A number N is called Deficient if the sum of its proper divisors is less than the number it self N.

3. And a number N is called Abundant if this sum of its proper divisors is exceeds N (number it self)

Enhancement: So instead of solving problem No.23, we will write a code to determent the group that a number belongs to. As we trying to make a general cods, we will ask the user to enter a number then we will call the function to collect all the divisors of N and get its sum and gives it a name according to the classification we just talk about.



The Code:


# Python: Non-abundant sums
# Problem No.23 @ ProjectEuler
# We solve it in my way

num_divisors=[]

def get_num_group (num):

for x in range(1,num):

if num%x == 0:

num_divisors.append(x)

num =int(input(‘Enter a number: ‘))
div_sum =0

get_num_group(num)

for each in num_divisors:

div_sum = div_sum + each

print(‘\n Divisors of {} are,’.format(num),num_divisors)
print(‘ The sum of the Divisors is ‘,div_sum)
if div_sum == num :

print (‘ The number {} is Perfect Number’.format(num))
elif div_sum < num :

print (‘ The number {} is Deficient ‘.format(num))
else:

print (‘ The number {} is Abundant ‘.format(num))






Follow me on Twitter..



Python: Square Digit Chain



Python: Square Digit Chain
ProjectEuler Problem No.92

Here we have a mathematical definition called Happy Number..

A Happy Number is defined by the following process:

Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either:
equals 1 (where it will stay), or
it loops endlessly in a cycle that does not include 1.
(Wikipedia).


In ProjectEuler the task stated in this problem as ” How many starting numbers below ten million will arrive at 89?”

Enhancement: Here we will do something else, we will try to solve the task and post the answer to the projecteuler portal, BUT we are not talking about this here, we will use the concept of this task to generate chains of looped number and I will use it later in another post (project) and trying to represent this chains in a graphic way.

So to do this we need two functions, First one will read a number, get its digits, squaring each digit and get the summation. To keep our eyes on the numbers we need to store it, so we will use list called the_chain.

To check if we have reach a closed chain then we need to ask if the new number (sum of square digit) exists in the chain list or not. If exists we finish and will return the chain for more manipulating.


I will solve this on my way .. 🙂

In this code we will do the following:

1. We will ask the user to enter a number.

2. We will run the function on that number.

3. Outputs:

If we ends with 1 then we have a Happy Number.

If we have closed chain (current number exists in the chain) then we will have tow cases:

If the current number is the same as the start number, then we will call this “Perfect Chain“. Otherwise we will call it “Tail Chain



The Code:


# Square digit chain.
# Pprojecteuler problem No 92

num = 1
the_chain=[]

def get_square_digit_chain(n):

tot=0

the_chain.append(n)

while n != 0:

tot=0

for each in str(n):

tot= tot + int(each)**2

n = tot

if n in the_chain:

return n

else:

the_chain.append(n)

#We ask the user to enter a number.
num =int(input(“Enter a number “))

chain_closed = get_square_digit_chain(num)
if chain_closed == 1:

print(“We have a Happy Number”)

print(the_chain,’This is Open Chain’)
else:

if chain_closed == num:

print(“We have a Perfect Chain”)

print(the_chain,’Closed on’,chain_closed)

else:

print(“We have a Tail Chain”)

print(the_chain,’Closed on’,chain_closed)






Follow me on Twitter..



Python: Digit fifth Powers



Python: Digit Fifth Powers
Projecteuler Problem No.30

This was an easy task and I solve it on my mobile during a brain resting session 😜. I will just copy the problem statement as it is in ProjectEuler ..



Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:

1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44

As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
Read it on Projecteuler


My Problem When I start solving the task i was wondering how far i should check the numbers? We can’t just go for ever, we must stop in some range. I search the web for such cases an i fond a post that clearing this with a formula. I will explain this in my way.




Finding the Upper Limits:
1. We are talking about Power (P=5)
2. We are using the (Base ten) numbers, so the highest digit is 9. Then:
3. 9 power 5 (9p5 = 59049)
4. The digits in (59049) are D=5.
5. Finally, The Formula is (D * 9p5), 5 * 59049 = 295245
6. So, The Upper Limits = 295245



According to the “Finding the Upper Limits” section, if we want to use the power (4) then the upper limit will be:
9p4 = 6561
6561 is a 4 digits
upper limit = 4 * 6561 = 26244



The Code: [The code is for power 4]

# Digit Fifth Powers
# Projecteuler Problem 30

num = 2
pdig = []
wefound = []
thesum = 0

while num < 26244 :

for each in str(num):

pdig.append(int(each) ** 4)

for x in pdig:

thesum = thesum + int(x)

if thesum == num:

wefound.append(num)

print(‘\n Number =’, num)

print(‘ Digits Power 4 =’, pdig)

print(‘ The Sum ‘, thesum)

num = num + 1

pdig = []

thesum = 0

thesum = 0

for x in wefound:

thesum = thesum + x

print(“\n The Numbers that the 4th power of its each digit = itself are: “,wefound)
print(” The Sum of the numbers is: “,thesum)






Follow me on Twitter..



Python: Self Power



Python: Self Powers
Problem No.48 on ProjectEuler

Another easy task in Problem No.48. We have to find the power of each number to itsefl in the range of 1 to 1000 and get the sum of all numbers, then to find the last ten digits of the series.

In this Task we will save the powers in a set name powers then we run a for loop
to get the sum of all elements in the lest, later will reade the last ten digits.

Enhancment In this problem I will not do any more than solving the problem, but if we want to enhance the project, we can ask the user to enter a range and we perform the function on that range of numbers.




The Code:

powers=[]

def get_power(num):

powers.append(num**num)

for x in range(1,1001):

get_power(x)

sum=0
for each in powers:

sum=sum+each

print(powers)
print (‘the sum is ‘,sum)






Follow me on Twitter..



Python : Curious Number



Python: Curious Number
Problem No.34 in ProjectEuler

Definition: A number is Curious Number if the factorial of their digits equal to the number itself.

Example: 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Our Task: We will write two functions, first one will get (return) all digits in the number, then another function to get the factorial of each digits in that number then with If statement we will examine the result.
Enhancement: We will ask the user to enter a number and we will check if it is a Curious Number.
We will reuse some of our functions that we wrote in previous posts.



The Code:


digs=[]
print(‘\nEnter a number to see if it is a Curious Number or not.’)
num=input (‘\nEnter a number: ‘)
num=input (‘Enter a number: ‘)
tot=0
# To get the digits In a number
def digits_in_num (num):

for each in str(num):

digs.append(each)

# To get the Factorial of a number
def Factorial_digit_sum(num):

if (num == 0) :

return 1

else:

return num * Factorial_digit_sum(num-1)

for each in digs:

print(‘factorial :’,each,’ is ‘,Factorial_digit_sum(int(each)))

tot = tot + Factorial_digit_sum(int(each))

print(‘\nTotal sum of the Factorial of each digits is: ‘,tot)
if int(num) == tot:

print(num ,’Is a Curious Number.’)
else:

print(num ,’Is NOT Curious Number.’)









Follow me on Twitter..



Python: Multiples of Numbers

April 29, 2019 Leave a comment


Python: Multiples of 3 and 5
Problem No.1 in ProjectEuler

This is very easy, very short task to work on, the task as is in ProjectEuler like this “Find the sum of all the multiples of 3 or 5 below 1000.”

My way, as i like to do open code works for any numbers, we will ask the user to enter three numbers, num1 and num2 will be as (3 and 5) in the task, my_range will be as the 1000. So the code can get the sum Multiples of any two numbers in a ranges from 1 to my_range.

Check the answer if you like.













The Code:


# Multiples of 3 and 5
# ProjectEuler: Problem 1

def Multiples_of_N (num1,num2,my_range):

tot=0

for t in range (1,my_range):

if t %num1==0 or t%num2 ==0 :

tot = tot + t

return tot

print ‘\nDescription: This function will take three variables, two numbers represint the what we want to get there Multiples, then we ask for a range so we will start from 1 to your range.\n’
num1=int(input(‘Enter the first number:’))
num2=int(input(‘Enter the second number:’))
my_range =int(input(‘Enter the range (1, ??):’))

total=Multiples_of_N (num1,num2,my_range)

print ‘\nYou entered ‘,num1,’,’, num2,’ So the sum of all multiples of those number in range (1-‘,my_range,’) = ‘,total






Follow me on Twitter..