Python Forum

Full Version: Hard time with prime factors in the task.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey people.Im trying to do some harder python challenges to learn some new things. Given a string,and a number, I have to get an ascii value of a char, get the largest prime factor of the number and add it to the ascii value, ans also wrap-around values to a 0-127, and my code is:

def ascii_cipher(m, n): #message,number
        #Getting prime factorization of n:
        i = 2
        if i * i <= n:
            if not n % i:
                i = n//i
                if not n%(i**(1/2)):
                    i = int(i**(1/2))
        
        #Storing the int values of chars:      
        z_val = [ord(x)+i for x in m]
    
        #Getting the overflow point 
        def int_overflow(val):
            if val > 127:
                return (val % 128)
            if val < 0:
                return val % 128
            return val
        #Use the round up func:
        y_val = [int_overflow(x) for x in z_val]
        #Return the encrypted result
        return "".join(chr(x) for x in y_val)
If you have some math degree, you will most likely say that Im fkn retarded, and you will be right.
End of the story, thx for your attention.
Or maybe wait, I would be happy to understand it a bit - As far as I can tell my prime factors are wrong in 47/50 cases, but how to do it properly?
To get the prime factors of a number:
  • Start with factor = 2, and all_factors = []
  • As long a number is evenly divisible by factor, divide number by factor and append factor to all_factors.
  • Increase factor by 1
  • Repeat the last two steps until number == 1.