Reputation:
I'm relatively new to python and thus trying to set myself up running some simple algorithms. Here's the first problem from project euler, although there are other solutions available to the same problem in python, but I've tried a different approach.
In crux the idea is to find the sum of all multiples of 3 or 5 less than 1000. This is my code.
def main():
num = input('Insert number:')
output = sumOfMultiples(num)
print(output)
def sumOfMultiples(param):
j = 0
i = 0
for i in range(i, param):
if (i % 3 ==0) or (i % 5 == 0) and (i % 15 != 0):
j = j + i
return j
if __name__ == '__main__':
main()
This is the error that I get
Traceback (most recent call last):
File "/Users/Soumasish/PycharmProjects/MultiplesOf3And5/Main.py", line 21, in <module>
main()
File "/Users/Soumasish/PycharmProjects/MultiplesOf3And5/Main.py", line 7, in main
output = sumOfMultiples(num)
File "/Users/Soumasish/PycharmProjects/MultiplesOf3And5/Main.py", line 15, in sumOfMultiples
for i in range(i, param):
TypeError: 'str' object cannot be interpreted as an integer
Process finished with exit code 1
Upvotes: 0
Views: 34184
Reputation: 1
num = int(input("enter the number : "))
lt = []
for i in range(num):
if (i%3==0 or i%5==0):
lt.append(i)
sum_of_lt=sum(lt)
print(sum_of_lt)
Upvotes: 0
Reputation: 479
Instead of checking each number by dividing it by 5 and 3 we can easily do it in O(1) with formula.
n=int(input())
a=(n-1)/3
b=(n-1)/5
c=(n-1)/15
ans=(3*a*(a+1)/2)+(5*b*(b+1)/2)-(15*c*(c+1)/2)
print(ans)
Upvotes: 0
Reputation: 32189
You need to cast your input as an int:
def main():
num = int(input('Insert number:'))
output = sumOfMultiples(num)
print(output)
Furthermore, you can reduce your second method as follows. I checked and it still gives the correct answer:
def sumOfMultiples(param):
sum = 0
for i in range(param):
if (i % 3 ==0) or (i % 5 == 0):
sum += i
return sum
Upvotes: 1
Reputation: 15934
This is an issue with types, when you take an input in with:
num = input('Insert number:')
num
is a string type. You can see this if you use type(num)
. Then later you try to take a modulo with num
and the modulo is not a defined operation with a string.
If you make the type correct the problem will go away:
num_str = input('Insert number:')
output = sumOfMultiples(int(num_str)) #this makes the input string an int first
Upvotes: 0