I am a complete python beginner and I am trying to solve this problem :
A number is called triangular if it is the sum of the first n positive integers for some n For example, 10 is triangular because 10 = 1+2+3+4 and 21 is triangular because 21 = 1+2+3+4+5+6. Write a Python program to find the smallest 6-digit triangular number. Enter it as your answer below.
I have written this program:
n = 0
trinum = 0
while len(str(trinum)) < 6:
trinum = n*(n+1)/2
n += 1
print(trinum)
And it only works in the python I have installed on my computer if I say while len(str(trinum)) < 8:
but it is supposed to be while len(str(trinum)) < 6:
. So I went to http://www.skulpt.org/ and ran my code there and it gave me the right answer with while len(str(trinum)) < 6:
like it's supposed to. But it doesn't work with 6 with the python i have installed on my computer. Does anyone have any idea what's going on?
In Python 3, division is always floating point division. So on the first pass you get something like str(trinum) == '0.5'
. Which isn't what you want.
You're looking for integer division. The operator for that is //
.
The division operator changed in Python 2.x to 3.x. Previously, the type of the result was dependent on the arguments. So 1/2
does integer division, but 1./2
does floating point division.
To clean this up, a new operator was introduced: //
. This operator will always do integer division.
So in Python 3.x, this expression (4 * 5)/2
is equal to 10.0
. Note that this number is less than 100, but it has 4 characters in it.
If instead, we did (4*5)//2
, we would get the integer 10
back. Which would allow your condition to hold true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With