Nearest multiplication of a variable in Python

I’m new to Python and I need your help for a problem.

I’ve a variable « a ». With some integer multiplication between « p » and « z », I would find the nearest multiplication of « a ». After z=z-1 and we try it with the same process while z>=1. But I don’t know how to say that for Python!!
Here is my code :

def base(a,m):
    if m = 2:
        return bin(a)
    if m = 16:
        return hex(a)     
some_times = m - 1
while a != 0:
    while o < a:
        i = i + 1
        o = m^i 
        p = m^(x-1)
    if o < a:
        #I am blocked here, I would say something like that : while p * some_times isn’t nearest of a : some_times= some_times - 1
        list.append(p)
        # nb_list.append(the number that we find where I’m blocked)
        a = a-p

# I haven’t finished my code yet, sorry !

Thank you for your help

Cordially

It’s not really clear what you’re looking for, what should get multiplied with what? Either way it’ll be best if you show us the code you already have, and show which parts you’re missing or aren’t working.

Please make sure to enclose the code in triple backticks (```) to make a code block, so indenting stays the same.

Thanks @airtower-luna ,
I’ve added my code, that will be able to convert automatically a number of a base between 2 and 10 in another base between 2 and 10 (and hexadecimal)

So, are you really looking for the integer multiple of p that’s nearest to a, or (starting with a high multiple) the first one that’s smaller than a? Because with the "try the next smaller some_times" thing it kind of seems like the latter.

1 Like

The two methods are I think good but I think that you are right, it’s can be more easy to start with the smaller of some_times (so 1) and add one by one to the max of some_times. So, how can I do that ?

Thanks very much for your answer

Which way around makes more sense depends on what you’re actually looking for. Could you answer that? :wink:

1 Like

So, @airtower-luna , after a long reflection I think :thinking: that I search to have the max number of times where p * 1 fits in a, adding one by one to 1, to reach the limit of some_times.
I hope I’d be clear
Thanks for all your answers

From your code your second factor (some_times, I’m just going to use s for brevity) seems to have the upper, exclusive bound of m. So the easiest way would be to go down from there and return the first s for which the product with p is smaller than a:

# find the largest integer s < m where s * p < a
def find_factor(a, m, p):
    for s in range(m - 1, -1, -1):
        if (s * p) < a:
            return s

Ranges are extremely useful when you need, well, a range of numbers. In this case we’re looking at a range from m - 1 to (exclusive) -1, with steps of -1.

1 Like