views:

113

answers:

5
a = 218500000000

s = 6
f = 2
k = 49
d = k + f + s

r = a
i = 0

while (r >= d):
  r = r - d
  #print ('r = ',r)
  i = i+1
  #print ('i = ',i)

print (i)

I think it does what I expect it to, but its way too slow to calculate such a large number, I waited 5 mins for i to print (while python used 100% cpu to calculate..), but it didn't. Is there a more efficient way of rewriting this piece of code so I can see how many iterations (i) it takes to complete?

Many thanks

+2  A: 

Isn't a division what you're looking for?

danielkza
+4  A: 

You can use i = a/d. :D

NawaMan
And `r = a % d`.
NawaMan
Oh, is division faster than addition/subtraction? I'd love to know why! :)
Nimbuz
Got the answer btw, 3833333333.33. Still, would like to know why division is faster?
Nimbuz
@:Nimbuz, That depends, division of power-two number like 2, 4, 8, ... is as fast as addition and subtraction. Even when the number is not power-two number, doing so division is still faster than so many addition/subtraction. Also with modern hardware, the division is performed with a the same clock cycle as addition/subtraction.
NawaMan
@Nimbuz, if you had to multiply `1000*234` would you sum `234` a thousand times or would you apply the multiplication algorithm?
Nick D
@:Numbuz, In your case, you are doing more that just a few addition/subtraction. In each loop, you do one add for `i`, one subtract for `r` and a condition of `r` and `d`. AND you are doing that million of times :p.
NawaMan
@Nimbuz, About the decimal `.33`. You can cast it back to in using `(int)a/d`. :-D Cheer!
NawaMan
A: 

try 3833333333.3333333333333333333333. AKA r / d.

RCIX
+4  A: 
r = (a % d)
i = (a / d)

Use the modulo and division operators.

There is also a divmod function to calculate both together:

i, r = divmod(a,d)
Will
+1 for a one-liner. :-D
NawaMan
A: 

Looks like you are doing truncating division to me. That is, you want to find out how many times d goes into a without knowing the remainder.

a = 218500000000
s = 6
f = 2
k = 49
d = k + f + s

i = a // d

print (i)
Martin