Sum of Odd Numbers loop printing twice - python

M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0
while M <= N:
if M % 2 == 1:
sum = sum + M
M = M + 1
print(sum)
This is my python code, every time I run the program, it prints the number twice. (1 1 4 4 9 9 etc.) Just confused on why this happening - in intro to computer programming so any help is appreciated (dumbed down help)

My guess is the print statement is not indented inside the if statement properly. As the sum wont increase for an even number and every other number is even
Make sure you have everything indented properly
M = eval(input("Input the first number "))
N = eval(input("Input the second number(greater than M) "))
sum = 0
while M <= N:
if M % 2 == 1:
sum = sum + M
print(sum)
M = M + 1

My best bet would be to add M++ line after the scope of if statement.
What really is happening that your increment only works when it is inside the if statement but this is logically incorrect because it should increment everytime loop executes.

Get rid of eval() you really do not need it. and replace it with int(). By default input() is a string by default so int() converts it to an integer.
You are using a reserved keyword sum
Try running sum.__doc__. You will see that sum is actually an inbuilt function. You should not create a variable the same name as an inbuilt function. However you can use an underscore (described in pep8) and this will create a working variable.
Corrected code:
M = int(input("Input the first number "))
N = int(input("Input the second number(greater than M) "))
sum_ = 0
while M <= N:
if M % 2 == 1:
sum_ = sum_ + M
M = M + 1
print(sum_)

Related

How to write a for loop program that finds the sum of all odd numbers in a range, but does not use the if function

I need to write a code that asks for user input 'num' of any number and calculates the sum of all odd numbers in the range of 1 to num. I can't seem to figure out how to write this code, because we had a similar question about adding the even numbers in a range that I was able to figure out.
I've also added the lines of code that I've written already for any critiques of what I may have done right/wrong. Would greatly appreciate any help with this :)
total = 0
for i in range(0, num + 1, 1):
total = total + i
return total
total = sum(range(1, num + 1, 2))
if you really need a for loop:
total = 0
for i in range(1, num+1, 2):
total += i
and to make it more exotic, you can consider the property that i%2==1 only for odd numbers and i%2==0 for even numbers (caution: you make your code unreadable)
total = 0
for i in range(1, num+1):
total += i * (i % 2)
You can invent a lot more ways to solve this problem by exploiting the even-odd properties, such as:
(-1)^i is 1 or -1
i & 0x1 is 0 or 1
abs(((1j)**i).real) is 0 or 1
and so on
The range function has three parameters: start, stop, and step.
For instance: for i in range(1, 100, 2) will loop from 1-99 on odd numbers.
Easiest solution
You can use math formula
#sum of odd numbers till n
def n_odd_sum(n):
return ((n+1)//2)**2
print(n_odd_sum(1))
print(n_odd_sum(2))
print(n_odd_sum(3))
print(n_odd_sum(4))
print(n_odd_sum(5))
1
1
4
4
9
Using filter:
start_num = 42
end_num = 500
step = 7
sum([*filter(lambda x: x % 2 == 1, [*range(start_num, end_num+1, step)])])
You can use the math formula (works every time):
num = int(input("Input an odd number: "))
total = (1+num)**2//4
print(total)
Output:
Input an odd number: 19
100
total = 0
num = int(input())
for i in range(num+1):
if i%2 == 1:
total += i
print (total)
The % operator returns the remainder, in this case, the remainder when you divide n/2. If that is 1, it means your number is odd, you can add that to your total.
You can of course do it in 1 line with python, but this might be easier to understand.

Factors of a number using Python recursive function

I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)

Sum of all prime numbers between 1 and N in Python

I'm new to programming. While trying to solve this problem, I'm getting the wrong answer. I checked my code a number of times but was not able to figure out the mistake. Please, help me on this simple problem. The problem is as follows:
Given a positive integer N, calculate the sum of all prime numbers between 1 and N (inclusive). The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains one line of input containing N. For each testcase, in a new line, print the sum of all prime numbers between 1 and N.
And my code is:
from math import sqrt
sum = 0
test = int(input())
for i in range(test):
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(max)) + 1
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
print(sum)
For input 5 and 10, my code is giving output 6 and 48 respectively, while the correct answer is 10 and 17 respectively. Please, figure out the mistake in my code.
Here, I implemented simple program to find the sum of all prime numbers between 1 to n.
Consider primeAddition() as a function and ip as an input parameter. It may help you to solve your problem.Try it.
Code snippet:
def primeAddition(ip):
# list to store prime numbers...
prime = [True] * (ip + 1)
p = 2
while p * p <= ip:
# If prime[p] is not changed, then it is a prime...
if prime[p] == True:
# Update all multiples of p...
i = p * 2
while i <= ip:
prime[i] = False
i += p
p += 1
# Return sum of prime numbers...
sum = 0
for i in range (2, ip + 1):
if(prime[i]):
sum += i
return sum
#The program is ready... Now, time to call the primeAddition() function with any argument... Here I pass 5 as an argument...
#Function call...
print primeAddition(5)
This is the most broken part of your code, it's doing the opposite of what you want:
res = x%y
if res==0:
sum = sum + x
break
You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:
from math import sqrt
T = int(input())
for _ in range(T):
N = int(input())
sum_of_primes = 0
if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2
for number in range(3, N + 1, 2):
for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number
print(sum_of_primes)
OUTPUT
> python3 test.py
3
5
10
10
17
23
100
>
A slight modification to what you have:
from math import sqrt
sum = 0
test = int(input())
max = int(input())
for x in range(test,max+1):
if x == 1:
pass
else:
half = int(sqrt(x)) + 1
for y in range(2,half):
res = x%y
if res==0:
break
else:
sum = sum + x
print(sum)
Your biggest error was that you were doing the sum = sum + x before the break rather than outside in an else statement.
PS: (although you can) I'd recommend not using variable names like max and sum in your code. These are special functions that are now overridden.
Because your logic is not correct.
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
here you check for the factors and if there is a factor then adds to sum which is opposite of the Primes. So check for the numbers where there is no factors(except 1).
from math import sqrt
test = int(input())
for i in range(test):
sum = 0
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(x)) + 1
if all(x%y!=0 for y in range(2,half)):
sum = sum + x
print(sum)
First of all, declare sum to be zero at the beginning of the for i loop.
The problem lies in the if statement at almost the very end of the code, as you add x to the sum, if the res is equal to zero, meaning that the number is indeed not a prime number. You can see that this is the case, because you get an output of 6 when entering 5, as the only non-prime number in the range 1 to and including 5 is 4 and you add 2 to the sum at the beginning already.
Last but not least, you should change the
half = int(sqrt(max)) + 1
line to
half = int(sqrt(x)) + 1
Try to work with my information provided and fix the code yourself. You learn the most by not copying other people's code.
Happy coding!
I believe the mistake in your code might be coming from the following lines of code:
for x in range(3,max+1):
half = int(sqrt(max)) + 1
Since you are looping using x, you should change int(sqrt(max)) to int(sqrt(x)) like this:
for x in range(3,max+1):
half = int(sqrt(x)) + 1
Your code is trying to see if max is prime N times, where you should be seeing if every number from 1-N is prime instead.
This is my first time answering a question so if you need more help just let me know.

Anyway to inverse factorial function?

So the question comes like this, I'm new to python:
def factorial_cap(num): For positive integer n, the factorial of n (denoted as n!), is the product
of all positive integers from 1 to n inclusive. Implement the function that returns the smallest
positive n such that n! is greater than or equal to argument num.
o Assumption: num will always be a positive integer.
# Examples
# factorial_cap(20) output is 4 since 3!<20 but 4!>20
# factorial_cap(24) output is 4 since 4!=24
# factorial_cap(1) output is 1 since 1!=1
# And here is what I got
def factorial_cap(num):
n = 1
for i in range (1,num+1):
n = n*i
I'm pretty sure this is the right function for factorial def. But I just couldn't figure out, instead of getting the 'total value', how can I just get the right output as I posted example above?
Btw, should I use 'return' at the end of def, or it does not matter in this case?
There needs to be a test for when the current total is greater than or equal to the requested number. So you can use the condition of a while loop to perform that check, and increment a counter, i, that keeps track of the current iteration. Then it's a matter of returning the current value of i that produced the value >= the required number:
def factorial_cap(num):
n = 1
i = 1
while n < num:
i += 1
n *= i
return i
>>> factorial_cap(20)
4
>>> factorial_cap(24)
4
>>> factorial_cap(25)
5
>>> factorial_cap(1)
1
>>> factorial_cap(3628800)
10
You want a return but that isn't n, but i
def factorial_cap(num):
n = 1
i = 0
while True:
i += 1
n = n*i
if n >= num:
break
return i
print(factorial_cap(20))
print(factorial_cap(24))
print(factorial_cap(1))

Recursion function for counting the number of digits in a number?

So I know that this is something simple that can be done without a recursion function but I need to know the backside to this as I can't seem to figure out how to write this using recursion. im using this so far
n = int(raw_input("What is n? "))
def digit(n):
if n< 10:
return 1
else:
new = n/10
print 1 + digit(new/10)
return 1 + digit(new/10)
digit(n)
Now if I type in a number such as 33 then it outputs 2 but if I do a longer number then it doesn't print it properly and I was unsure as to what exactly it wrong with it.
The problem is,
new = n/10
return 1 + digit(new/10)
You are already dividing the number by 10, in new = n / 10, which reduces the last digit and you are again dividing it by 10 before calling digit. So, you are ignoring 1 digit in every recursive call.
Instead, you can simply do
return 1 + digit(n / 10)
or
new = n / 10
return 1 + digit(new)
#!/usr/bin/python
n = int(raw_input("What is n? "))
def digit(n):
if n < 10:
return 1
else:
return 1 + digit(n/10)
print digit(n)
You can do like this too.
def counter(number):
if(number == 0):
return 0
return counter(int(number/10)) + 1
number = 1998
print(counter(number)) // it will print 4

Categories

Resources