Python Forum
math problem using recursion?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
math problem using recursion?
#11
You could use recursion to build the tree. The key is to suppose that the problem is solved. Let func() be a function that takes a number as argument and returns None if it is not a semi-prime or the root of this semi-prime's tree if it is a semi-prime.

We need to define what the root of a tree will be. We'll take a tuple ((factor0, factor1), (subroot0, subroot1)). For this we could use a namedtuple. Here is an algorithm
Root = namedtuple('Root', 'factor subroot')

def func(number):
    try:
        fac0, fac1 = decompose_semi_prime_in_factors(number)
    except NotSemiPrime:
        return None
    root0 = func(int(f'{fac0}{fac1}'))
    root1 = None
    if fac0 != fac1:
        root1 = func(int(f'{fac1}{fac0}'))
    return Root((fac0, fac1), (root0, root1)) 
Reply
#12
The longest chain length could be millions , no ? Or is the start number limited?
Reply
#13
Ok, I got that alright. Here:

        try:
            divisors(newList[passes])
            passes += 1
        except:
            break
It seems to give the same results as yours. I have since added more code to make
it automatic. If I'm going to be searching millions of start numbers I can't do
it by hand.
I also tried to put in a counter for max chain length (inside the 'íf len(div) == 2:'
statement but it's not accurate. Since each 'level' of the tree can have anywhere
from 0 up to 2^(n-1) leaves, I may have to put in some conditionals to keep track,
although I'm not sure how that would work yet.

Quote:You could use recursion to build the tree.

Ok, I'll look at that also.
Reply
#14
(Sep-03-2020, 02:34 PM)mnh001 Wrote: Ok, I got that alright. Here:
Could not have done it better! :-)

Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#15
Thanks for the help. Sometimes the logic behind these things eludes me.
I think we can say this one is solved. :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Math Problem cryxma 2 1,920 Dec-21-2020, 09:53 PM
Last Post: Gribouillis
  GCF function w recursion and helper function(how do i fix this Recursion Error) hhydration 3 2,539 Oct-05-2020, 07:47 PM
Last Post: deanhystad
  Math problem in Python - pyqt5 rwahdan 6 5,736 Jun-18-2019, 08:11 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020