The question I'm trying to solve is here: https://projecteuler.net/problem=6
I tried this but all that was printed were two zeroes:
sumsquare = 0
ssum = 0
def sumsquaredif(n):
for i in range(1, n+1):
num = i ** 2
num += sumsquare
i += ssum
squaresum = ssum**2
print (squaresum)
print (sumsquare)
return
sumsquaredif(10)
And then of course I'd have to add the code to subtract sumsquare from squaresum and print that. But this preliminary code isn't working. I'd really appreciate it if someone could help. I'm still a beginner. Thank you!
Your += assignments are the wrong way! num += sumsquare is adding the sum to the current number, not the other way around, and similar for ssum. Also, the sum variables should be declared inside of the function.
def sumsquaredif(n):
sumsquare = 0 # inside function
ssum = 0 # inside function
for i in range(1, n+1):
num = i ** 2
sumsquare += num # inversed
ssum += i # inversed
squaresum = ssum**2
Also, you could make that code much shorter by using list comprehensions:
sumsquare = sum(n for n in range(1, n+1))**2
squaresum = sum(n**2 for n in range(1, n+1))
Related
I'm a new at programming, I like solving this euler questions and I know there are solutions for this problem but it's not about the problem at all actually.
So, i managed to create a working function for finding example: 33. triangular number. It works but i couldn't manage to properly desing my while loop. I wanted to make it like, it starts from first triangular checks it's divisors make list of it's divisors, checks the length of the divisors, because problem wants "What is the value of the first triangle number to have over five hundred divisors?" . But i never managed to work the while loop. Thank you for reading.
nums = [1]
triangles = [1]
divisors = []
def triangularcreator(x):
if x == 1:
return 1
n = 1
sum = 0
while n!=0:
n += 1
nums.append(n)
for i in range(len(nums)):
sum += nums[i]
triangles.append(sum)
sum = 0
if x == len(triangles):
n = 0
return triangles[-1]
counter = 1
while True:
for i in range(1, triangularcreator(counter) + 1):
if triangularcreator(counter) % i == 0:
divisors.append(i)
if len(divisors) == 500:
print(triangularcreator(counter))
break
counter +=1
divisors.clear()
You should try to change a few things, starting with calculating just once the value of triangularcreator(counter) and assigning this value to a variable that you can use in different points of your code.
Second, you create a loop which will be calculate always triangularcreator(1). At the end of each iteration you increase the value of counter+=1, but then at the beginign of the new iteration you assignt it again value 1, so it will not progress as you expect. Try this few things:
counter = 1
while True:
triangle = triangularcreator(counter)
for i in range(1, triangle + 1):
if triangle % i == 0:
divisors.append(i)
if len(divisors) == 500:
print(triangle )
break
counter +=1
Also these two arrays nums = [1], triangles = [1] should be declared and initialized inside the def triangularcreator. Otherwise you would be appending elements in each iteration
Edit: I believe it is better to give you my own answer to the problem, since you are doing some expensive operations which will make code to run for a long time. Try this solution:
import numpy as np
factor_num = 0
n = 0
def factors(n):
cnt = 0
# You dont need to iterate through all the numbers from 1 to n
# Just to the sqrt, and multiply by two.
for i in range(1,int(np.sqrt(n)+1)):
if n % i == 0:
cnt += 1
# If n is perfect square, it will exist a middle number
if (np.sqrt(n)).is_integer():
return (cnt*2)-1
else:
return (cnt*2)-1
while factor_num < 500:
# Here you generate the triangle, by summing all elements from 1 to n
triangle = sum(list(range(n)))
# Here you calculate the number of factors of the triangle
factor_num = factors(triangle)
n += 1
print(triangle)
Turns out that both of your while loop are infinite either in triangularcreatorin the other while loop:
nums = [1]
triangles = [1]
divisors = []
def triangularcreator(x):
if x == 1:
return 1
n = 1
sum = 0
while n:
n += 1
nums.append(n)
for i in range(len(nums)):
sum += nums[i]
triangles.append(sum)
sum = 0
if len(triangles) >= x:
return triangles[-1]
return triangles[-1]
counter = 1
while True:
check = triangularcreator(counter)
for i in range(1, check + 1):
if check % i == 0:
divisors.append(i)
if len(divisors) >= 500:
tr = triangularcreator(counter)
print(tr)
break
counter +=1
Solution
Disclaimer: This is not my solution but is #TamoghnaChowdhury, as it seems the most clean one in the web. I wanted to solve it my self but really run out of time today!
import math
def count_factors(num):
# One and itself are included now
count = 2
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
count += 2
return count
def triangle_number(num):
return (num * (num + 1) // 2)
def divisors_of_triangle_number(num):
if num % 2 == 0:
return count_factors(num // 2) * count_factors(num + 1)
else:
return count_factors((num + 1) // 2) * count_factors(num)
def factors_greater_than_triangular_number(n):
x = n
while divisors_of_triangle_number(x) <= n:
x += 1
return triangle_number(x)
print('The answer is', factors_greater_than_triangular_number(500))
I am new to python and trying to write a program to add all the numbers starting from 1 through n and print their sum. Can anyone please tell me what is wrong with my code. I am getting 1 as an output.
def problem1_3(num):
sum_= 0
num = int(num)
for i in range(1,num):
sum_ = sum_ + i
print(sum_)
i+=1
return(sum_)
You are returning the sum_ on the first iteration of the function. You want to finish the for loop, and only then return it. Read more about loops in python, they are based on indentation, unlike some other languages.
Two mistakes that you are making in your code:
1- You are incrementing i by +1 but you don't have to do this because python will automatically increment loop variable.
2- You are returning your sum_ variable inside for loop that's why you got 1 as an output.
def problem1_3(num):
sum_= 0
num = int(num)
for i in range(1,num+1):
sum_ = sum_ + i
#print(sum_)
# i+=1
return(sum_)
ans = problem1_3(5)
print(ans)
Output:
15
So you are returning inside your for loop, so it does not go to completion.
but if you would like an easier more concise way to write that function,
def problem1_3(num):
return sum(range(num)) #for up to, but not including num
or
def problem1_3(num):
return sum(range(num+1)) #for up to, AND including num
Since you already have the range function, range produces a list of numbers. So range(5) is [0,1,2,3,4]
and summing them will get you 1+2+3+4
it's just a shorter way of doing the same thing.
If you don't have to use for loop, it's better to use recursion.
def problem1_3(num : int) -> int:
if num == 1:
return 1
else:
return num + problem1_3(num-1)
# 5 + problem1_3(4)
# 5 + 4 + problem1_3(3)
# 5 + 4 + 3 + problem1_3(2)
# 5 + 4 + 3 + 2 + problem1_3(1)
# 5 + 4 + 3 + 2 + 1
.
if you have to use loops.
your problem is when you are returning sum_. you should to finish your loop and after all, Outside the loop, return the sum:
def problem1_3(num : int) -> int:
sum_ = 0
for i in range(1, num+1):
sum_ += i
return (sum_)
According to me this code below should print the sum of first n integers but it is giving me name error on line 5. How do I fix this ?
def printsum(n):
n = int(raw_input())
for i in range(1,n+1):
j = i + 1
doublesum = i + j - n
total = doublesum / 2
print total
The variables i and j are local to the function printsum. Simply return the values from the function and use said values to do your calculation.
Try with this code copy and past. Because issue may be indentation
def printsum(n):
n = int(raw_input())
for i in range(1,n+1):
j = i + 1
doublesum = i + j - n
total = doublesum / 2
print total
return;
Your logic is make me confused too.
I am using following code to find sum of digits in Python but infinite loop gets started as I run program
def digit_sum(n):
k=str(n)
i=0
while i<range(len(k)):
l=int(i)
j=0
j=j+i
print j
i+=1
digit_sum(1234)
You have an indentation error.
So, for getting correct output try this way . You can check this code here .
def digit_sum(n):
k = str(n)
i = 0
j = 0
while i < len(k):
l = int(k[i])
j = j + l
i += 1
print j
digit_sum(1234)
The indentation is wrong. The while loop is outside of your function. Indent it to stay inside the function. Also give more meaningful names to your variables.
Its looks like you are new to python So i m going to help you out i have seen you code it seems like you have indentation problem and some logic problem also so i have updated it see it here
def digit_sum(n):
k = str(n)
j = 0 #sum for digits
i = 0
while i in range(len(k)):
#Add convert string to the int and add to the sum
j = j + int(k[i]);
#increment Counter
i = i+1
print j # print Sum
digit_sum(1234)
For more info about indentation you can See Here
So I have the code
def formula(n):
while(n < 11):
answera = 15/(-4)** n
print(answera)
n = n + 1
formula(1)
How can I add the outputs in condescending order?
For example,
first_output = (the output of n = 1)
second_output = (the output of n = 1) + (the output of n = 2)
third_output = (the output of n = 1) + (the output of n = 2) + (the output of n = 3)
and so on..
you need to define the variable answera outside the while loop, so that its shope should exists outside the loop , so that when you return the value the fully updated value can be returned. Something like this.
def formula(n):
answera = 0
while(n < 11):
answera += 15/(-4)** n
print(answera)
n = n + 1
print(answera)
formula(1)
Now it should give you the right result.
def formula(n):
while(n < 11):
answera += 15/(-4)** n
print(answera)
n = n + 1
The idea is that you will need to accumlate the value of 15/(-4)**n in one of the variables.. (here the answera) and keep printing it out.
I hope this answers your question.
There's some ambiguity in your question; do you want the sum of 'answera', or the sum of 'formula'?
If 'answera', then you can just replace "print" with "yield" and call "sum":
def formula(n):
while(n < 11):
answera += 15/(-4)** n
yield answera
n = n + 1
sum(formula(2))
This makes 'formula' a generator, and "sum" will iterate that generator until it's exhausted.
If you want the sum of multiple 'formula' calls, then follow the KISS principle, and wrap your function with another function:
# assuming that 'formula' is a generator like above
def mega_formula(iterations):
total = []
for i in range(1, iterations + 1): # b/c range indexs from zero
total.append(sum(formula(i))
return sum(total)