I want to write progarm, The function accepts two integers n, m as arguments Find the sum of all numbers in range from 1 to m(both inclusive) that are not divisible by n. Return difference between sum of integers not divisible by n with the sum of numbers divisible by n.
In my case, if is not working.
n = int(input("num "))
m = int(input("limit "))
for i in range(1, m+1):
sum1 = 0
sum2 = 0
if i % n == 0:
sum1 += i
else:
sum2 += i
print(f"{sum1} and {sum2}")
print(abs(sum2-sum1))
Take sum1 = 0 and sum2 = 0 outside the for loop; currently you are resetting those values at each iteration, so that it does not keep the sum.
n, m = 2, 10
sum1 = 0
sum2 = 0
for i in range(1, m+1):
if i % n == 0:
sum1 += i
else:
sum2 += i
print(f"{sum1} and {sum2}")
print(abs(sum2-sum1))
Output:
30 and 25
5
Bring your sum1 and sum2 outside of the loop, you're resetting them every time
not_n = []
with_n = []
def inputts(n, m):
# code
for x in range(1, m+1):
if x % n == 0:
with_n.append(x)
else:
not_n.append(x)
# now sum
nott_n = sum(not_n)
withh_n = sum(with_n)
#now substraction
subb=(withh_n-nott_n)
print(abs(subb))
inputts(5,100)
Related
This is a program to print a matrix whose sum of each row , column or diagonal elements are equal.
I have a working code but my program gives same output each time i run it. I need a program to print different matrix output for same input.
def matrix(n):
m = [[0 for x in range(n)]for y in range(n)]
i = n // 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal : ",int(n*(n*n+1)/2),"\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of the matrix : "))
matrix(n)
I am unsure whether this is what you are looking for, but one solution is to add a random number to each value of the matrix, as this doesn't break the property
a matrix whose sum of each row, column or diagonal elements are equal.
Here is how you could do it:
add = random.randint(0, 50)
m = [[v+add for v in row] for row in m]
Moreover, you can rotate and add two magic squares without loosing their property. Therefore, you can rotate the magic square you have and add it to the original. This can add some nonlinearity to the results.
def rotate(m): # 90 degrees counter clockwise
return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1, -1, -1)]
# add the matrix with its rotated version
m = list(map(lambda e: [sum(x) for x in zip(*e)], zip(m, rotate(m))))
I hope this helps!
I want my program to be able to print out the sum of all numbers below n that are divisible by 3 and also 5.
#!/bin/python3
import sys
import math
arr = []
arr3 = []
arr5 = []
tn = 1
sum1 = 0
sum2 = 0
t = int(input("How many test cases do you have? ").strip())
while t < 1 or t > 10**5:
print("go again, the number is not in the range")
t = int(input("How many test cases do you have? ").strip())
for i in range(t):
n = int(input("What number do you want to test? ").strip())
arr.append(n)
for x in range (0, len(arr)):
for b5 in range (0, arr[x], 5)
sum1 = sum1 + b5
for b3 in range (0, arr[x], 3)
sum2 = sum2 + b3
sum = sum1 + sum2
print(sum)
My idea was to let the secondary for loops iterate through the given number in increments and print each iteration into the sum. Somehow I cannot pass an argument into the for loop in the way that I present here. How do I make this approach work?
Edit:
#!/bin/python3
import sys
import math
arr = []
arr3 = []
arr5 = []
tn = 1
sum1 = 0
sum2 = 0
t = int(input().strip())
while t < 1 or t > 10**5:
print()
t = int(input().strip())
for i in range(t):
n = int(input().strip())
arr.append(n)
for x in range (0, len(arr)):
sum1 = 0
sum2 = 0
mo5 = arr[x]%5
mo3 = arr[x]%3
if mo5 == 0 or mo3 == 0:
arr[x] = arr[x]-1
for b5 in range (0, arr[x], 5):
sum1 = sum1 + b5
print(b5)
for b3 in range (0, arr[x], 3):
sum2 = sum2 + b3
sum = sum1 + sum2
I am also trying to exclude the integer located at arr[x], since the sum of the divisible numbers must be from divisible numbers below the number arr[x]. When I print out the result for 100, then it shows 0, 5, 0, 5, ... 95. This brings it to a total of 100 again. Why does this happen?
Your solution seems correct - but it seems u have a couple of syntax errors if you're using python
You also have to re-initialize sum1 & sum2 between test cases. Right now you get the total sum of all arrs rather than arr[x]-hopefully that makes sense. You also have to remove duplicate numbers from the sum. For instance, if you're getting the sum of all numbers up to 20 - you'll end up adding 15 twice as it is divisible by 3 and 5. So the inner for loops will add it twice to the sum. So you'll need to remove 15 to get rid of duplicates.
for x in range(len(arr)): #by default range starts at o. therefore, range(len(arr)) = range(0, len(arr))
sum1 = 0 # you forgot to initialize sum1
sum2 = 0 # you forgot to initialize sum2
duplicates = 0 #you have to remove duplicates from the answer
for b5 in range (0, arr[x], 5): #you have to add the colons here
sum1 = sum1 + b5
for b3 in range (0, arr[x], 3): #you have to add the colons here
sum2 = sum2 + b3
for dup in range(0, arr[x], 3*5): # removes duplicates from the final sum
duplicates = duplicates + dup
sum = sum1 + sum2 - duplicates
print(sum)
This is an O(n^2) solution - you can drop it down to O(n) using a little bit of math.
You'll notice that the inner for loops can be represented using the formula sum(n)=Σd*i=d*Σi-where the summation starts at i = 0, end at ⌊(n-1)/d⌋ and d is the divisor (in the case of your question d=3 or 5).
for b5 in range (0, arr[x], 5):
sum1 = sum1 + b5
(https://en.wikipedia.org/wiki/Summation)
There is a very common summation formula that is commonly used to convert summations into a closed-form expression (something with finite steps - which is O(1))
Σi=n*(n+1)/2
In the case of the inner loop - it would be sum(n) = d*(⌊(n-1)/d⌋)*(⌊(n-1)/d⌋+1)/2.
let,
f(n,d) = (⌊(n-1)/d⌋+1)/2
Therefore, the solution to your problem would be f(n,3)+f(n,5)-f(n,3*5)
Which would convert the inner for loops from O(n) to O(1). Which, means your entire solution would be O(n).
I'll let you figure out the code on your own. However, theoretically, there is a better solution; such that as arr grows indefinitely the work scales linearly rather than quadratically.
Create Array with input number (Eg. arr = [12, 15, 4] )
Iterate over the created Array
In for loop check if number are divisible by 3 and 5
Sample code:
arr = [12, 15, 4]
total = 0
for num in arr:
if num % 3 == 0 and num % 5 == 0:
total = total + num
print(total) # 15
There are several issues with your code:
You are using the len function to get the length of arr, but you haven't defined arr or assigned any values to it. You need to define arr and assign a list of numbers to it before you can iterate over it.
You are using the range function incorrectly in your for loops. The range function takes a start value, an end value, and an optional step value, but you are only providing the end value and step value. You need to provide the start value as well.
You are using the b5 and b3 variables to store the values from the range function, but you are not using them to calculate the sum of the numbers that are divisible by 3 and 5. You need to use these variables to calculate the sum.
You are defining the sum1 and sum2 variables inside the for loops, but you are not initializing them to 0 before adding the numbers to them. You need to initialize these variables to 0 before adding the numbers to them.
Here is how you could fix your code:
arr = [10, 20, 30, 40, 50] # Define the list of numbers
for x in range(0, len(arr)): # Iterate over the list of numbers
sum1 = 0 # Initialize sum1 to 0
sum2 = 0 # Initialize sum2 to 0
for b5 in range(0, arr[x], 5): # Iterate over the numbers in increments of 5
sum1 = sum1 + b5 # Add the number to sum1
for b3 in range(0, arr[x], 3): # Iterate over the numbers in increments of 3
sum2 = sum2 + b3 # Add the number to sum2
sum = sum1 + sum2 # Calculate the sum
print(sum) # Print the sum
arr = []
arr3 = []
arr5 = []
tn = 1
sum1 = 0
sum2 = 0
t = int(input("How many test cases do you have? ").strip())
while t < 1 or t > 10^5:
print("go again, the number is not in the range")
t = int(input("How many test cases do you have? ").strip())
for i in range(t):
n = int(input("What number do you want to test? ").strip())
arr.append(n)
for i in range(len(arr)):
if arr[i] % 3 == 0:
arr3.append(arr[i])
elif arr[i] % 5 == 0:
arr5.append(arr[i])
for i in range(len(arr3)):
sum1 = sum1 + arr3[i]
for i in range(len(arr5)):
sum2 = sum2 + arr5[i]
sum = sum1 + sum2
print(sum)
I have to calculate the sum of all the multiples of 3 and 5 (including themselves) in a range of a given N number (N excluded). I created a python code and it works with N = 10 but doesn't work for N = 100. I don't understand why.
This is the code:
#!/bin/python3
import sys
def multiples_sum(n):
sum1 = 0
for i in range(n):
if i % 3 == 0:
sum1 = sum1 + i
if i % 5 == 0:
sum1 = sum1 + i
return sum1
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(multiples_sum(n))
you are counting the multiples of 15 (= 3 * 5) twice.
your code should be
for i in range(n):
if i % 3 == 0:
sum1 += i
elif i % 5 == 0:
sum1 += i
note the elif instead of if.
alternatively:
for i in range(n):
if i % 3 == 0 or i % 5 == 0:
sum1 += i
or directly (as DeepSpace suggests in the comments)
sum1 = sum(i for i in range(n) if 0 in {i % 3, i % 5})
note that there is no need for looping at all: knowing that the sum of the integers from 1 to (and including) n is
def sum_to(n):
return ((n+1)*n)//2
you can get your number from:
sum1 = 5 * sum_to((n-1)//5) + 3 * sum_to((n-1)//3) - 15 * sum_to((n-1)//15)
(that could be generalized and made somewhat prettier... but i'm sure you get the idea in this form).
EDIT:
In the meantime I saw #DeepSpace's solution in the comments, particularly the one with the if 0 in {i % 3, i % 5})-check - which I definitely admire; this is really smart!
I think I'd go this way, if you're interested in a different approach:
N = 100
sum(set(list(range(0, N, 3)) + list(range(0, N, 5))))
# 2318
Because 10 is less than 15, which is the least common multiple of 3 and 5.
You need to treat the particular case of 15.
Here is the problem:
Surprisingly there are only three numbers that can be written as the
sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of
fifth powers of their digits.
And here is my code:
summ = 0
digit_sum = 0
i = 0
while i < 1000000:
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
else:
digit_sum = 0
i += 1
print(summ)
Can anyone find out that why I miss a value 4151 which should be one of the correct answer?
The problem in your code is you forgot to reset the digit_sum when you got an answer.
Put digit_sum = 0 before j = list(str(i)). You also start with i = 0. I suggest to start with i = 10 since the first 2 digit number is 10.
use this:
[i for i in range(10, 1000000) if i == sum(int(d) ** 5 for d in str(i))]
equivalent with:
[4150, 4151, 54748, 92727, 93084, 194979]
using sum:
sum(i for i in range(10, 1000000) if i == sum(int(d) ** 5 for d in str(i)))
equivalent with:
443839
4150 is also in solutions. The digit_sum is not set to 0 before 4151 step. You should set digit_sum = 0 in each step.
summ = 0
i = 10
while i < 1000000:
digit_sum = 0
j = list(str(i))
for x in j:
digit = int(x) ** 5
digit_sum += digit
if digit_sum == i:
summ += i
print(i)
i += 1
print(summ)
The answer to your question is that you don't reset digit_sum every time, only when digit_sum != i. If you remove the else statement, it should work correctly.
if digit_sum == i:
summ += i
print(i)
digit_sum = 0
i += 1
I want to find out the sum of numbers in a range say N which has exactly 2 ones in its binary representation.I wrote the code as:
N = int(raw_input())
sum1 = 0
for i in range(1, N + 1):
if bin(i)[2:].count('1') == 2:
sum1 = sum1 + i
This code takes a lot of time. Is there any faster way to do this calculation?
Try this code:
def two_bit_numbers(N):
bit0 = 0
bit1 = 1
while True:
n = (1<<bit1) + (1<<bit0)
if n > N:
break
yield n
bit0 += 1
if bit0 == bit1:
bit1 += 1
bit0 = 0
N = 100
sum1 = 0
for i in two_bit_numbers(N):
# print i, bin(i)
sum1 += i
print sum1
If we look at how to find number that have two '1' when written in binary, we get to two cases :
We have an element > 1 with 1 '1' in binary representation and we add 1 to it
We have an element that has two '1' in binary representation, and we multiply it by 2.
So, to look for the number of element matching this case, you could just do :
num = int(raw_input())
def get_numbers(N):
sum1 = []
sum2 = []
i = 2
while i < N:
# we add the elements of case 2
sum1.extend(sum2)
# we add the element of case 1
sum1.append(i+1)
sum2 = [2*x for x in sum1 if x > i]
# we check for the elements with one more number when written in binary
i *= 2
# sum1 now contains all elements with two '1' in binary between 0 and the power of 2 above N.
# we remove the elements above N
sum1 = [x for x in sum1 if x <= N]
# we sort the list
sum1.sort()
# we take the length of the list, of the number of elements with two '1' in binary between 0 and N
return sum1
print(get_numbers(num))
This should be faster, as we do not test every number between 0 and N, and have a log2(N) complexity.
Do not hesitate if you have any question about my method.
This method is slower than the one in the other answer (around 2 times slower)