Creating Python Factorial - python

Evening,
I'm an intro to python student having some trouble.
I'm trying to make a python factorial program. It should prompt the user for n and then calculate the factorial of n UNLESS the user enters -1. I'm so stuck, and the prof suggested we use the while loop. I know I didn't even get to the 'if -1' case yet. Don't know how to get python to calc a factorial with out just blatantly using the math.factorial function.
import math
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
print(num)

The 'classic' factorial function in school is a recursive definition:
def fact(n):
rtr=1 if n<=1 else n*fact(n-1)
return rtr
n = int(input("Enter n: "))
print fact(n)
If you just want a way to fix yours:
num = 1
n = int(input("Enter n: "))
while n > 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
If you want a test for numbers less than 1:
num = 1
n = int(input("Enter n: "))
n=1 if n<1 else n # n will be 1 or more...
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Or, test n after input:
num = 1
while True:
n = int(input("Enter n: "))
if n>0: break
while n >= 1:
num *= n
n-=1 # need to reduce the value of 'n' or the loop will not exit
print num
Here is a functional way using reduce:
>>> n=10
>>> reduce(lambda x,y: x*y, range(1,n+1))
3628800

You are actually very close. Just update the value of n with each iteration:
num = 1
n = int(input("Enter n: "))
while n >= 1:
num *= n
# Update n
n -= 1
print(num)

I am new to python and this is my factorial program.
def factorial(n):
x = []
for i in range(n):
x.append(n)
n = n-1
print(x)
y = len(x)
j = 0
m = 1
while j != y:
m = m *(x[j])
j = j+1
print(m)
factorial(5)

You could do something like this.
def Factorial(y):
x = len(y)
number = 1
for i in range(x):
number = number * (i + 1)
print(number)

#Factorial using list
fact=list()
fact1=input("Enter Factorial Number:")
for i in range(1,int(fact1)+1):
fact.append(i)
print(fact)
sum=fact[0]
for j in range(0,len(fact)):
sum*=fact[j]
print(sum)

i=1
f = 1
n = int(input("Enter n: "))
if n>=0:
while n >= i:
f=i*f
i+=1
print(f)
I am using this code in order to calculate factorial and it works.(Python 3.8)

Related

Python Add up numbers from 1 to N (WHILE LOOP) and keep adding

I'm trying to add up all the number from 1 to N and print the result and then keep asking the user to enter number till the number zero is entered. I can make it sum the numbers and end the while but can't make it keep asking for more numbers like this: https://pastebin.com/9pWDT6su
num = int(input('N: '))
sum = 0
while num != 0:
while num < 0:
num = int(input('ERROR - N: '))
sum = sum + num
num = num - 1
print('Sum: ', sum)
# If I put this outside the WHILE it'll work but it won't allow me to
# keep adding numbers
num = int(input('N: '))
print('END')
Try this :
num = int(input('N: '))
while num != 0:
sum=0
while num > 0:
sum = sum + num
num = num - 1
print('Sum: ', sum)
num = int(input('N: '))
print('END')
If you want the sum of 1-n for all numbers remove sum=0 inside while
Try this:
num = int(input('N: '))
sum_ = 0
while True:
if num < 0:
num = int(input('ERROR - N: '))
elif num == 0:
break
else:
sum_ = sum_ + num
print('Sum: ', sum_)
num = int(input('N: '))

I am trying to find the sum of all the prime numbers below a certain number. if the initial number is prime we return it

def sumPrimes(num):
sum = 0
if num>1:
for i in range(1, num):
if num % i == 0:
pass
else: sum = sum + i
return sum
print(sumPrimes(3))
i don't know why this isnt working pls help. I am trying to find the sum of all the prime numbers below a certain number. if the initial number is prime we return it.
Meaby It will help u
# Program to check if a number is prime or not
num = 407
# To take input from the user
#num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
If you want to do this efficiently it's more complex than you might have imagined.
def genprime():
yield 2
D = {4:[2]}
q = 3
while True:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 2
def isprime(n):
if isinstance(n, int) and n >= 2:
g = genprime()
s = int(n ** 0.5)
while True:
d = next(g)
if d > s:
return True
if n % d == 0:
break
return False
def sumPrimes(n):
if isprime(n):
return n
g = genprime()
sum = 0
while (np := next(g)) < n:
sum += np
return sum
print(sumPrimes(12))
You'll need Python 3.7+ for this
This seems to work. If you want it to add 1 as a prime number change the second range to include 1.
def sumPrimes(num):
sum = 0
if num > 1:
if all(num % n for n in range(2, num)) == True: #check of prime
return num
else:
for i in range(2, num):
if all(i % n for n in range(2, i)) == True: #if you want it to add the number 1 as a prime number change this range to range(1,i)
sum += i
else:
continue
return sum
You can use is_prime to check if the number is prime in the loop:
import math
def is_prime(x):
for num in range(2, int(math.sqrt(x)) + 1):
if x % num == 0:
return False
return True
def sumPrimes(num):
return sum([x for x in range(2,num) if is_prime(x)])

Write a Python program that reads a positive integer n and finds the average of all odd numbers between 1 and n

This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number

Check given number is prime or not, if it is prime then find factorial of that number, if it is not prime then print sum-of-digit of that number

The sum of digit is running well, but Why is the factorial section not working? Is there any mistakes that I made with the if else, or the break ?
NUM = int (input ("Enter a number "))
if NUM > 1:
for x in range (2, NUM):
if (NUM % x) == 0:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
break
else:
factorial = 1
for I in range (1, NUM + 1,1):
factorial *= I
print (factorial)
else:
temp = NUM
sod = 0
while temp > 0:
remainder = temp % 10
sod += remainder
temp = temp//10
print (sod)
Your break statement on line 12 is outside the if statement, so the for loop will break after the first pass regardless of the value of NUM. Are you sure you didn't mean to indent the break another four spaces?
# example of factorial with prime numbers
num = int(input("Enter a number"))
factorial = 1
if num%2 == 0:
for i in range(1, num + 1):
factorial = factorial*i
print("The factorial of ",num," is",factorial)
Below code checks if the number is prime or odd number. if its prime it finds the factorial of that number and if its odd number then it sums the range of the number. Hope its what you were looking for.
NUM = int(input("Enter number here"))
if NUM > 0:
if NUM % 2 == 0:
factorial = 1
for i in range(1, NUM +1):
factorial = factorial*i
print(factorial)
else:
sum_of_NUM = 0
for x in range(NUM+1):
sum_of_NUM += x
print(sum_of_NUM)
else:
print("something you want to put")

How to find first n number of prime numbers in python?unable to follow the scope of a variable?

f=0
c=1
n=raw_input("Enter the value of n")
while c<n:
for i in range(2,100):
for j in range(1,i):
if i%j == 0:
f =f+1
if f == 1:
print i
c = c+1
f = 0
If n is 5 then the output should print the first 5 prime numbers.
2,3,5,7,11
You have a few mistakes. You do not parse n as integer, you have an unnecessary loop, you inistailise c with a wrong value.
Here is a corrected version
c = 0
n=int(raw_input("Enter the value of n"))
i = 2
while True:
for j in range(2,i):
if i % j == 0:
break
else:
print i
c = c + 1
if c == n:
break
i += 1
Copy of answer to this question.
You're only checking the value of count at the end of the for loop so you will always end up with the full range of 1-100 being tested. Why is the range limited to 100?
You don't need a for loop at all. Use the while loop to keep finding primes until you have num of them.
Try something like:
import math
def isPrime(num):#this function courtesy of #JinnyCho
if num == 1:
return False
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num % i == 0:
return False
return True
def getPrimes(num):
count = 0
i = 1
highPrime = None
while count < num:
if isPrime(i):
count += 1
yield i
i += 1
n = int(raw_input("Enter the value of n: "))
list(getPrimes(n))

Categories

Resources