Integer division
jm.suresh@no.spam.gmail.com
jm.suresh at gmail.com
Thu Jun 7 05:57:45 EDT 2007
On Jun 7, 2:15 pm, Hamish Moffatt <ham... at cloud.net.au> wrote:
> jm.sur... at no.spam.gmail.com wrote:
> > Hello all,
> > I have two integers and I want to divide one by another, and want to
> > get an integer result which is the higher side whenever the result is
> > a fraction.
> > 3/2 => 1 # Usual behavior
> > some_func(3, 2) => 2 # Wanted
>
> > Any easier solution other than int(math.ceil(float(3)/2))
>
> The normal solution is to add (divisor-1) to the dividend before division.
>
> Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct.
>
> But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct.
>
> Hamish
What about this?
>>> def div_ceil(a, b):
... if a%b:
... return ((a/b)+1)
... else:
... return (a/b)
...
>>> div_ceil(3,2)
2
>>> div_ceil(-3,2)
-1
>>> -3%2
1
>>> -(3%2)
-1
>>> div_ceil(-5,2)
-2
>>> div_ceil(5,2)
3
More information about the Python-list
mailing list