Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I've tried looking up some questions that were already on StackOverflow for project Euler problem 1 but not much has helped me. This is my code, it runs, but it's not correct. not sure whats wrong?
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += 1
return sum
print (sumOfMultiples(15))
You are not using i at all. When the number meets the condition (divisible by 3 or 5), you want to add it, not 1.
sum += 1
should be
sum += i
The question asks for "the sum of all the multiples of 3 or 5 below 1000". You're adding 1 to the sum instead of adding the multiple of 3 or 5 to the sum.
So sum += 1 should be sum += i.
import time
#Recording start time of the program
start=time.time()
#A variable to store the sum
result=0
#calculating the sum for all the numbers below 1000
for i in range(1,1000):
#Checking the the condition
if i%3==0 or i%5==0:
result=result+i
print("Sum of all numbers that are multiples of 3 or 5 below 1000 is",result)
print("Execution time of program is",time.time()-start)
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
print (sumOfMultiples(15))
In place of sum+=1 write sum+=i.
Here is a single-liner for you to ponder:
print sum([x for x in xrange(1,1000) if x%3==0 or x%5==0])
or you could also do it like this:
print sum([[0,x][x%3==0 or x%5==0] for x in xrange(1,10**3)])
try using this:
def sumOfMultiples(number):
sum = 0
for i in range(1,number):
if i % 3 == 0 or i % 5 == 0:
sum += i ## You needed to add i, not 1. Probably just a type-o as they are similar looking characters.
print(sum)
(sumOfMultiples(1000)) ## Also Euler1 requires this input to be 1000 for correct answer.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Given the list of integers, X,
https://www.google.com/url?q=https://docs.google.com/document/d/1TjeNYpZ_PbdBISlJPF-_WqULBc1WpuYthLClovjB3Rs/edit?usp%3Dsharing&sa=D&ust=1594968749928000&usg=AFQjCNG8bAv1lX8pXr4CYcgaDfYFxcbgCg
I want to write code to count how many integers are strictly larger than all the integers to their right excluding the last digit since it doesn’t have a number to its right. E.g. for [2,3,1] the answer should be 1 while for [12,4,4,2,2,3] the answer is 2. I have no clue how to write the code. I will appreciate any guidance on how to proceed.
Here's a solution that does that in O(N), where N is the size of the list.
l = [12,4,4,2,2,3]
def max_so_far(l):
m = 0
for i in l[::-1]:
m = max(m, i)
yield m
sum([x>y for x,y in zip(l[-2::-1], max_so_far(l))])
How about this code?
mylist = list(map(int,input().split()))
count = 0
for i,item in enumerate(mylist):
if i == len(mylist) - 1: #here we excluded the last element for a check
break
check = max(mylist[i+1:])
if check < item:
count = count + 1
print(count)
I am understating this problem in two way:
counter = 0
for i in range(len(list_of_number)):
for j in range(i, len(list_of_number)):
if list_of_number[j] > list_of_number[i]:
counter += 1
Here, after it gets the first value, it scans all the list. The code that follow it will check only the number's right neighbour
counter = 0
for i in range(len(list_of_number)-1):
if list_of_numbers[i+1] > list_of_numbers[i]:
counter +=1
How about this?
def counter(L):
return sum([1 for i in range(len(L)-1) if L[i] < L[i+1]])
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Finding the sum of all the divisors of a number, without including that particular number that is being divided.
For example if we want to find the divisors of number 6 they would be 1,2,3. Number 6 should be included as it is a divisor, but for this scenario we are not considering it.
Note:- number 3 and 4 are not included since, when you divide number 6 by number 3, there would be a remainder.
A divisor is a number that divides into another without a remainder.
def sum_divisors(n):
sum = 0
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print(sum_divisors(3)) # Should sum of 1 # 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 # 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 # 114
I think I got it:
def sum_divisors(n):
return sum([i for i in range(1, n)
if n % i == 0])
print(sum_divisors(0))
print(sum_divisors(3)) # Should sum of 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
Output
0
1
55
114
You could use a combined filter() and lambda() function
num = 36
div_sum = sum(list(filter(lambda div : num % div == 0 , range(1, num))))
# divisors : [1, 2, 3, 4, 6, 9, 12, 18]
# divisors sum : 55
print('divisors sum : ', div_sum)
We need to find the divisors of the number first, and then sum them. Finding out if a number is a divisor of another number is pretty simple:
if x % y == 0:
is_divisor = True
Modulo - % - returns the remainder of a division. 9 % 2 = 1. 10 % 3 = 1. However, we'll need to know which numbers to check. We could just loop through every number up to our input:
for i in range(n):
if n % i == 0:
is_divisor = True
...but that's too much. For example, we know that the highest possible divisor of n that isn't n itself, is 1/2n if n is even, and lower if it's not. Instead, let's focus on getting each pair, and then check if we should continue. We also need to store all of these numbers, so lets create some lists:
lower_divisors = []
upper_divisors = []
We'll want to know what our current highest lower divisor and lowest highest divisor are, and also know where to start. We can populate the lower divisor list with 1 and the highest with n. We can worry about removing n later.
lower_divisors = [1]
upper_divisors = [n]
continu = True
while continu:
# Let's get the last item in each list
highest_low = lower_divisors[-1]
lowest_high = upper_divisors[-1]
for i in range(highest_low + 1, lowest_high):
if n % i == 0:
lower_divisors.append(i)
upper_divisors.append(n // i)
break
continu = False
# If we've left the loop, we have all of our divisors.
lower_sum = sum(lower_divisors)
higher_sum = sum(upper_divisors) - n #Gotta take it back out!
sm = lower_sum + higher_sum
return sm
That should be a fast way to achieve your goal, without making your computer work harder - but... it's a lot more steps to write. I wrote it in far more steps to make it clear what I was doing and to be readable, but it could definitely be trimmed up a lot.
Upon running the code, the simple method of looping through each number from 1 to n starts to really add up when n is over 8 digits. 9 digit numbers were taking around 12-16 seconds on my machine. The longer approach above returns 32-digit values for n in under 1/10th of a second.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I already got the following part and I think its a fast and clear way and I dont need it to be faster:
for num in range(2,1000):
if all(num%i!=0 for i in range(2,num)):
print num
But how can I find the max difference of all the prime numbers I got and put that as the final result?
You can proceed like that:
biggest_prime = 2
for num in range(2,1000):
if all(num%i!=0 for i in range(2,num)):
biggest_prime = num
print "Difference: " + str(biggest_prime - 2) # outputs 995
Basically, you just store the last found prime, and when you're out of the loop you will have the value of the highest prime below 1000. You can then substract 2 to it.
If you don't like the fact that the 2is hard-coded, you can add a second variable lowest_prime that will change value only once.
Don't output each prime; store it in a list, so that once you have the full list, you can do what you like with the primes.
primes = []
for num in range(2, 1000):
if all(num % i != 0 for i in range(2, num)):
primes.append(num)
More briefly,
primes = [num for num in range(2, 1000) if all(num % i != 0 for i in range(2, num)]
primes = []
for num in range(2, 1000):
if all(num % i != 0 for i in range(2, num)):
primes.append(num)
x = primes[-1] - primes[0]
print(x)
so is this okay?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Am new to programming and I just started studying and practicing. I started with python and am at for loops now. I kinda coded something that’s getting confusing for me because I can’t seem to understand how the code arrived at that output. Can someone please explain it to me. Would be very grateful.
Here’s the code I did:
a = range(1,20)
total = 0
for i in a :
if i%3==0 or i%5==0 :
total new = total + i
print (total new)
And the output was 18.
a = range(1,20)
Your program is creating a range of numbers between 1 and 19 (ranges go to one less than the max number you specify) like [1, 2, 3, 4, ..., 19]
total = 0
Your program is initializing the variable total to equal 0
for i in a:
You start looping through the range you made earlier, the first iteration i=1, the next i=2 and so on until i=19
if i % 3 == 0 or i % 5 == 0:
You are selecting only the data where the modulo of 5 or 3 is 0. For example:
3 % 3 == 0 (0 remainder)
4 % 3 == 1 (1 remainder)
Now altering your variable to a reasonable name (without spaces) that will actually utilize the variable we initialized above
total = total + i # alternatively written "total += i"
This says that every time the value i is evenly divisible by 3 or 5 we will add it to our total
print(total)
We show the final result after adding values. You incorrectly scripted your program to do this though so it only showed the largest value that was evenly divisible by 5 or 3 which is 18.
When scripted correctly:
a = range(1, 20)
total = 0
for i in a:
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
Outputs
78
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
For Project Euler, question #1:
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.
I am trying to use Python, and I have the following code:
def findNums():
numsToAdd = []
num = 1
while num < 999:
if 3 % num == 0 or 5 % num == 0:
numsToAdd.extend([num])
num +=1
#print(num) optional
for i in numsToAdd:
lastNum = 0
addition = numsToAdd[i] + lastNum
lastNum = numsToAdd[i]
print(lastNum)
findNums()
But I get the following error when I try to run it:
addition = numsToAdd[i] + lastNum
IndexError: list index out of range
Could someone please tell me what this is and how to fix it?
You have a few issues:
if 3 % num == 0 or 5 % num == 0:
Your conditionals are backward. How you have it set up now, you are checking if 3 or 5 is evenly divisible by num, not if num is evenly divisible by 3 or 5.
for i in numsToAdd:
Assume that numsToAdd has the following values when you get to this point: [100, 500].
When you get to addition = numsToAdd[i] + lastNum you are saying the following:
addition = numsToAdd[100] + lastNum
and
addition = numsToAdd[500] + lastNum
There isn't a 100th or 500th element. Instead, you can remove the indexing (to keep your existing format):
addition = i + lastNum
You could also do this to add up all the values in the list in one line:
sum(numsToAdd)
This can replace the entire for loop.
Finally, your first while is wrong:
Find the sum of all the multiples of 3 or 5 below 1000.
You are checking for everything less than 999. Change your while loop:
while num < 1000:
The problem with your code is that your list numsToAdd has just 465 items in it.
Instead of this:
numsToAdd[0]
numsToAdd[1]
numsToAdd[2]
.
.
numsToAdd[462]
numsToAdd[463]
numsToAdd[464]
You are doing this:
numsToAdd[3]
numsToAdd[5]
numsToAdd[6]
.
.
numsToAdd[459]
numsToAdd[460]
numsToAdd[462]
The error occurs because your list index is out of range! There is no numsToAdd[465]!