Beginner here- trying to make a simple python program that will compute/answer this problem:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Currently this is what I have:
a = 0
b = 0
while a < 1000:
a = a + 3
print (a)
while b < 1000
b = b + 5
print (b)
This will print all the numbers being considered. I just need to add them together and that's my answer.
I would like one of two things to happen, instead of the code that I have written:
I would like all of this to happen internally, and therefore not have to use the "print" function. The just print the sum of all of those multiples.
I would like all of this stuff to print, but then I want to be able to print the sum of all of them too. Is there a way to make the computer take the value of everything it has printed?
Actually this problem can be solved in O(1) instead of O(N) without using any loops or lists:
The required sum is the sum of all multiples of 3 plus sum of all multiples of 5 minus the sum of multiples of (3*5=15) below the given number 1000 (LIMIT=999). The sums are calculated as a sum of arithmetic series.
It can be calculated in following way:
LIMIT=999
# Get the upper bounds for the arithmetic series
upper_for_three = LIMIT // 3
upper_for_five = LIMIT // 5
upper_for_fifteen = LIMIT // 15
# calculate sums
sum_three = 3*upper_for_three*(1 + upper_for_three) / 2
sum_five = 5*upper_for_five*(1 + upper_for_five) / 2
sum_fifteen = 15*upper_for_fifteen*(1 + upper_for_fifteen) / 2
# calculate total
total = sum_three + sum_five - sum_fifteen
# print result with Python 3
print(int(total))
The result is:
>>>
233168
It is possible to do this in one line in Python using a generator expression:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
The range(1000) produces all the integers from 0 to 999 inclusive. For each one of those integers, if it is divisible by 3 or divisible by 5, then it is included in the result. The sum(...) function adds up all those numbers, and finally print(...) prints the result.
I would use a for loop to iterate over each number in your selected range. Then you can check if the modulus % is equal to 0, meaning it has no remainder when divided by those values, if so, add it to the total.
total = 0
for num in range(1000):
if num % 3 == 0 or num % 5 == 0:
print(num)
total += num
>>> total
233168
While a for loop would work, you could also use a generator expression and sum:
sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)
def sum_multiply (n):
data = []
for num in range (1, n):
if num % 3 == 0 or num % 5 == 0:
data.append(num)
return sum(data)
sum_multiply(1000)
total=0
i=0
while i<1000:
if i%3==0 or i%5==0:
print(num)
total+=i
i+=1
print("Total is: ")
**with python**
print(sum([i for i in range(1,1000) if i%3==0 or i%5==0 ]))
Related
The question that I have is trying to find the highest degree of divisibility
I have a list of numbers and I to divide them by themseleves
Example below
a = [2,2,5,4,12,64]
2 can be divided by [2,2]
5 can be divided by [5]
4 can be divided by [2,2,4]
12 can be divided by [2,2,4,12]
64 can be divided by [2,2,4,64]
That means the highest degree of divisibility is 4
Here is the code the I wrote so far.
b = len(a)
for i in range(b):
c = np.divide(a, a[i])
print(c)
```
I am wondering how can write the code to output the highest degree of divisibility.
Thanks!
try like below
def test():
a = [2,2,5,4,12,64]
maxv = -999
for i in a:
counter=0
for j in range(len(a)):
if i%a[j]==0:
counter+=1
if counter>maxv:
maxv=counter
print('highest number:',maxv)
test()
Since the numbers you're checking for divisibility will give the same results (like the two 2's), iterate over the set of unique numbers and then try to divide each number in that set by each number in the original list a. Using the modulo operator %, each time the remainder is 0, increase the counter for that number and add the final result to a list. Then take the maximum:
a = [2,2,5,4,12,64]
divs = []
for num in set(a):
count = 0
for denom in a: # denominator
if num % denom == 0:
count += 1
divs.append(count)
print(divs) # to see the count of the divisors
# [4, 2, 3, 1, 4]
print('highest degree:', max(divs))
# highest degree: 4
This can be reduced to almost a one-liner using a list comprehension for the outer loop. For the inner 'count'ing loop, use a generator expression like so: in Python, True evaluates to 1 and False evaluates to 0. So if we sum the number of times that division check is True, we get the count:
divs = [sum(num % denom == 0 for denom in a) for num in set(a)]
print('highest degree:', max(divs))
And, since we're taking the max() of it, we could turn the outer loop into a generator expression as well:
highest = max(sum(num % denom == 0 for denom in a) for num in set(a))
I have some code where I must find the multiples of number 3 and then summarize them
I have done the first job, I mean I found all the multiples of number 3 with for loop but I can't summarize all the numbers which I found.
I have tried so many times and tried to find the solution on google, but could not find
x = 3
for number in range(1000):
if number%x == 0:
print(number)
I need now the sum of all the numbers which indicates on this code, when you run this code you can see that there is publishing only the numbers that can divide by 3 now I need the sum of them
It's easier than you think:
sum(range(0, 1000, 3))
Explanation:
range is defined as such: range([start], end[, step]) so range(0, 1000, 3) means go from 0 to 1000 in steps of 3
The sum function will sum over any iterable (which includes range)
You need a variable to hold the sum (If you are in learning stage):
x = 3
total = 0
for number in range(1000):
if number % x == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
Edit:
To answer your comment use condition or condition:
x = 3
y = 5
total = 0
for number in range(10):
if number % x == 0 or number % y == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
You could create a result variable to which you can keep adding:
result = 0
x = 3
for number in range(1000):
if number%x == 0:
result += number
print(result)
The best way is using filter and sum:
# any iterable variable
iterable_var = range(100)
res = sum(filter(lambda x: x % 3 == 0, iterable_var), 0)
I used a for loop to print the numbers between 0 and 100 that are multiples of three. Now I have to print the ones that are divisible by two and I cant seem to get it to work properly.
I need to show both and I did that below, but is there a way to incorporate the second for loop into the first one in order to print both without printing the divisible ones in the same loop as the multiples of three.
Code:
for x in range(0,100,3):
print(x)
for n in range(0,100,3):
if n % 2 == 0:
print(n)
for x in range (0,100,3):
print("Multi of 3: " + str(x))
if(x % 2 == 0):
print("Div by 2: " + str(x))
if(x % 3 == 0 AND x % 2 == 0 ):
print("Both: " + str(x))
You need to add an if statement to check for numbers which are divisible by 2. If a number is evenly divisible by 2 then the number remainder will be 0. To check this, you can use the % (modulo) operator.
So, you'd have:
for x in range (0, 100, 3):
# check if x is evenly divisible by 2
# i.e. is the remainder zero when divided by 2
if x % 2 == 0:
print(x)
Alternatively, you could go up in steps of 6, since 6 is the LCM of 2 and 3.
for x in range(0, 100, 6):
print(x)
for x in range (0,100,2):
print(x)
This will print the ones divisible by 2 excluding 100
not a expert in python but logicaly all language has a modulo operator
sum = 0
for i in range (yourange):
if (i % 3 == 0)
sum += i
return sum
I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why this code is grossly wrong?
n = 0
x = n<1001
while (n < 1001):
s = x%3 + x%5
print s
You've got a few mistakes:
x is a boolean type
Your loop never ends
adding values to mimic lists?
Edit
Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:
sum = 0
for i in range(1001):
if(i % 3 == 0 or i % 5):
sum += i
print(sum)
(Python 3)
You need to stop while at some point by incrementing n. Here is some code:
nums = []
n = 0
while (n < 1001):
# in here you check for the multiples
# then append using nums.append()
n += 1
This creates a loop and a list that accounts for every number in 0 to 1000. In the body, check for either condition and append to the list, then print out the values in the list.
num is a list where you are going to store all the values that apply, (those numbers who are divisible by 3 and 5, which you calculate with modulo). You append to that list when a condition is met. Here is some code:
nums = []
n = 0
while (n < 1001):
if(n % 3 == 0 or n % 5 ==0):
nums.append(n)
n += 1
print(n) #or for loop for each value
Explanation: a list of numbers called num stores the numbers that are divisible by 3 or 5. The loop starts at zero and goes to 1000, and for all the values that are divisible by 3 or 5, they will be added to the list. Then it prints the list.
Of course there is a simpler approach with a range:
for i in range(1001):
if(i % 3 == 0 or i % 5 == 0):
print(i)
This will print out all the values one by one. It is 1001 because the upper limit is exclusive.
true=1
false=0
so:
x = n<1001
we have x=1 because 0<1001 is true
s = x%3 + x%5
the remainder of 1/3 is 1 and 1/5 is 1
In your code:
1. x=n<1001 - generates a boolean value; on which we can't perform a mathematical operation.
In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.
Solution 1:
Below code will help you out.
s=0
for i in range(1,1002):
if( i%3 == 0 or i%5 == 0):
s = s + i
print(s)
Solution: 2
There is one more approach you can use.
var = [i for i in range(1,1002) if i%3==0 or i%5 ==0]
print(sum(var))
Not sure if I should've posted this on math.stackexchange instead, but it includes more programming so I posted it here.
The question seems really simple, but I've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it won't gives me the right answer when coding it! I made two different solutions for it, which both gives me the wrong answer. The first solution gives me 265334 while the second one gives me 232169. The answer is 233168, so the second solution is closer.
I should mention this is a question from Project Euler, the first one to be precise.
Here's my code. Any ideas what's wrong?
nums = [3, 5]
max = 999
result = 0
for num in nums:
for i in range(1,max):
if num*i < max:
result += num*i
print result
result = 0
for i in range(0,max):
if i%3 == 0 or i%5 == 0:
result += i
print result
You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a list comprehension:
>>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0]
Then use sum to get the total:
>>> sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
<<< 233168
Or even better use a generator expression instead:
>>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
Or even better better (courtesy Exelian):
>>> sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))
range(k,max) does not include max, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use range(1,1000) instead.
I like this the most:
def divisibles(below, *divisors):
return (n for n in xrange(below) if 0 in (n % d for d in divisors))
print sum(divisibles(1000, 3, 5))
The problem with your first solution is that it double-counts multiples of 15 (because they are multiples of both 3 and 5).
The problem with your second solution is that it doesn't count 999 (a multiple of 3). Just set max = 1000 to fix this.
result = 0
for i in range(0,1000):
if (i % 3 == 0 or i % 5 == 0):
print i
result = result + i
print result
Output:
0
3
5
6
9
.
.
.
993
995
996
999
233168
max = 1000 # notice this here
result = 0
for i in range(0,max):
if i%3 == 0 or i%5 == 0:
result += i
print result
This works, but use 1000 for max, so it includes 999 too.
I know this was 3 months ago but as an experiment because I am new to python I decided to try and combine some of the other people answers and I came up with a method you can pass the max number to and the divisors as a list and it returns the sum:
def sum_of_divisors(below, divisors):
return sum((n for n in xrange(below) if 0 in (n % d for d in divisors)))
max = 1000
nums = [3, 5]
print sum_of_divisors(max, nums)
There are floor(999/3) multiples of 3, floor(999/5) multiples of 5, and floor(999/15) multiples of 15 under 1000.
For 3, these are: 3 + 6 + 9 + 12 +... + 999 = 3 * (1 + 2 + 3 + 4 +...+333)
= 3 * (333 * 334 / 2) because the sum of the integers from 1 to k is k*(k+1)/2.
Use the same logic for the sum of multiples of 5 and 15. This gives a constant time solution. Generalize this for arbitrary inputs.
I know this is from 6 years ago but I just thought id share a solution that found from a math formula that I thought was interesting as it removes the need to loop through all the numbers.
https://math.stackexchange.com/a/9305
def sum_of_two_multiples(nums, maxN):
"takes tuple returns multiples under maxN (max number - 1)"
n1, n2 = nums = nums[:2]
maxN -= 1
def k(maxN, kx):
n = int(maxN / kx)
return int(kx * (0.5 * n * (n+1)))
return sum([k(maxN, n) for n in nums]) - k(maxN, n1*n2)
Outputs the follows
print(sum_of_two_multiples((3,5), 10))
# 23
print(sum_of_two_multiples((3,5), 1000))
# 233168
print(sum_of_two_multiples((3,5), 10**12))
# 233333333333166658682880
I think only the last few lines from your code are important.
The or statement is the key statement in this code.
Also rater than setting the max value to 999, you should set it to 1000 so that it will cover all values.
Here is my code.
ans=0
for i in range(1,1000):
if(i%3==0 or i%5==0):
ans += i
print(ans)
input('press enter key to continue');#this line is only so that the screen stays until you press a key
t = int(input())
for a in range(t):
n = int(input().strip())
sum=0
for i in range(0,n):
if i%3==0 or i%5==0:
sum=sum+i
print(sum)
You can also use functional programming tools (filter):
def f(x):
return x % 3 == 0 or x % 5 == 0
filter(f, range(1,1000))
print(x)
Or use two lists with subtraction of multiples of 15 (which appears in both lists):
sum1 = []
for i in range(0,1000,3):
sum1.append(i)
sum2 = []
for n in range(0,1000,5):
sum2.append(n)
del sum2[::3] #delete every 3-rd element in list
print(sum((sum1)+(sum2)))
I like this solution but I guess it needs some improvements...
here is my solution:
for n in range(100):
if n % 5==0:
if n % 3==0:
print n, "Multiple of both 3 and 5" #if the number is a multiple of 5, is it a multiple of 3? if yes it has has both.
elif n % 5==0:
print n, "Multiple of 5"
elif n % 3==0:
print n, "Multiple of 3"
else:
print n "No multiples"
this is my solution
sum = 0
for i in range (1,1000):
if (i%3)==0 or (i%5)==0:
sum = sum + i
print(sum)
count = 0
for i in range(0,1000):
if i % 3 == 0 or i % 5 ==0:
count = count + i
print(count)
I know it was 7 years ago but I wanna share my solution to this problem.
x= set()
for i in range(1,1001):
if (i % 3) == 0:
x.add(i)
for j in range(1,1001):
if (j % 5) == 0:
x.add(j)
print(sum(x))
I had to do it in range 1 , 100
This is how I did it.
For i in range(1,100):
If i ÷ 3 == 0 and i ÷ 5 == 0:
print(i)
So with 1000 you just change the 100 to 1000
I had to find the multiples of 3 and 5 within 100 so if you need 3 or 5 just change it to or and it will give you more answers too. I'm just starting to learn so correct me if I'm wrong
Here is the code:
count = 1000
m = [3, 5, 3*5]
result = 0
Sum = 0
for j in m:
result = 0
for i in range(count):
if i*j < 1000:
result = result + i*j
elif i == (count - 1):
if j < 15:
Sum = result + Sum
elif j == 15:
Sum = Sum - result
print(Sum)
total = 0
maxrange = input("Enter the maximum range") #Get the maximum range from the keyboard
print("")
max = int(maxrange)
for i in range (0,max):
if i%3 == 0 or i%5 ==0:
total = total +i
print (total)