My goal is to build a programm, that says is a number prime or not.
A positive whole number n > 2 is prime if no number between 2 and sqrt(n)
divides n.
Here is my code:
import math
def main():
print("Prime number or not")
try:
N = -1
while N<2:
print("Error!Enter numbers greater than two")
N = int(input("Enter the right number:"))
values = list(range(2,round(math.sqrt(N))))
for i in values:
if i%N !=0:
continue
x = print("The number is not prime")
elif i%N ==0:
break
x = print("The number is NOT prime")
print(x)
except ValueError:
print("Error!Print correct number")
except NameError:
print("Error!Print the numbers")
main()
But is shows a syntax error in line
elif i%N ==0:
Please, give me some advice how to correct this error and about the code in general. I am new in learning Python, so any help and critic will be good!
Thanks.
If you wanted this to be your whole programme, here is my solution:
# Get num
num = input('Input a whole number: ')
# Is num valid
try:
num = int(num)
if num < 1 or num > 1000000000000:
print('Your field cannot be greater than one quantillion or less than one.')
else:
# Is num 2 or 5, if yes, prime.
if num != 2 and num != 5:
# Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
lastNum = str(num)[-1]
if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
print('Your number is composite.')
if lastNum == '5':
print(str(num) + ' is divisible by 5.')
else:
print(str(num) + ' is divisible by 2.')
else:
# List multiples of 3 less than 123, call it multiplesOf3.
multiplesOf3 = []
appendMultiple = 0
for i in range(40):
appendMultiple += 3
multiplesOf3.append(appendMultiple)
# Get sum of all numbers in num, name is sumOfNum
sumOfNum = 0
numStr = str(num)
for i in range(len(numStr)):
sumOfNum += int(numStr[i])
# Is sumOfNum in multiplesOf3?
numMultipleOf3 = sumOfNum in multiplesOf3
if numMultipleOf3 == True:
print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
else:
print('Your number is prime.')
else:
print('Your number is prime')
except:
print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
But if you wanted this to be just a function, here is my solution (Make sure you put in a parameter, it requires 1 argument; put in your number.)
def isPrime(num):
try:
num = int(num)
if num < 1 or num > 1000000000000:
print('Your field cannot be greater than one quantillion or less than one.')
else:
# Is num 2 or 5, if yes, prime.
if num != 2 and num != 5:
# Is the last number of num 0, 2, 4, 5, 6, or 8, if yes, composite.
lastNum = str(num)[-1]
if lastNum == '0' or lastNum == '2' or lastNum == '4' or lastNum == '5' or lastNum == '6' or lastNum == '8':
print('Your number is composite.')
if lastNum == '5':
print(str(num) + ' is divisible by 5.')
else:
print(str(num) + ' is divisible by 2.')
else:
# List multiples of 3 less than 123, call it multiplesOf3.
multiplesOf3 = []
appendMultiple = 0
for i in range(40):
appendMultiple += 3
multiplesOf3.append(appendMultiple)
# Get sum of all numbers in num, name is sumOfNum
sumOfNum = 0
numStr = str(num)
for i in range(len(numStr)):
sumOfNum += int(numStr[i])
# Is sumOfNum in multiplesOf3?
numMultipleOf3 = sumOfNum in multiplesOf3
if numMultipleOf3 == True:
print('Your number is composite.\n' + str(num) + ' is divisible by 3.')
else:
print('Your number is prime.')
else:
print('Your number is prime')
except:
print('Your field needs to be a whole number. Make sure there is no decimal points (i.e. 12.0 will not be accepted).')
Another way,
def isprime(n):
if min(n//2,n//3,n//5) == 1:
return True
elif min(n%2,n%3,n%5) == 0:
return False
return True
This is SO much shorter!
assuming that the indentation on the question is correct NOW, the problem is that your elif block doesn't have an if parent. It's also indented wrong, which even if you fix the first error will throw an IndentationError but that's almost beside the point.
for i in values:
if i%N !=0:
continue
x = print("The number is not prime") # huh? you've left the `if` block
elif i%N ==0: # under-indented
break
Related
I have to count the sum of all prime numbers that are less than 1000 and do not contain the digit 3.
My code:
def primes_sum(lower, upper):
total = 0
for num in range(lower, upper + 1):
if not num % 3 and num % 10:
continue
elif num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
total += num
return total
total_value = primes_sum(0, 1000)
print(total_value)
But still I don't have right result
def primes_sum(lower, upper):
"""Assume upper>=lower>2"""
primes = [2]
answer = 2
for num in range(lower, upper+1):
if any(num%p==0 for p in primes): continue # not a prime
primes.append(num)
if '3' in str(num): continue
answer += num
return answer
The issue in your code was that you were checking for num%3, which checks whether num is divisible by 3, not whether it contains a 3.
There is no error in this code but its not printing the result. Here, what could be the problem.
# Using WHILE LOOP
num = int(input('Enter any positive integer: '))
sum1 = 0
i = 1
if num <= 0:
print('Invalid Number.')
else:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
if sum1 == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
The problem lies here:
if num % i == 0. The == operator checks if the remainder of num/i is 0. If yes, then it updates i. But, if num % i is not 0, then it never adds anything to i. So, with each iteration, you are doing the same thing: num % i == 0.
You need to bring i = i + 1 outside if statement because i should increase regardless of whether the number is divisible or not.
Also, it is better to use i+=1. See difference between add and iadd
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
You set if num % i == 0: i += 1, so if num % i != 0, i will not be updated. you just add else after if num % i == 0.
num = int(input('Enter any positive integer: '))
sum1 = 0
i = 1
if num <= 0:
print('Invalid Number.')
else:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i += + 1
else:
i+=1
if sum1 == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
You set up an infinite while loop.
If i < num is true and num % i == 0 is false, the while loop will run infinitely. You can verify this by using a print statement inside the while loop. Like this:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
print('Passed the if statement')
If Passed the if statement gets printed multiple times then num % i == 0 is false and the if statement got ignored, and the while loop keeps running and ignoring the if statement again and again.
Once you figured out the problem, you could find out many solutions. I could suggest moving the incrementation of i out of the if statement so that whenever num % i == 0 results to false, i would be incremented and checked again. So the while loop could look like this:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
I need to check if a number is Lychrel number and if not to print the number of times the loop did until it got to the palindrome, for some reason it always print 0
num = input('please enter your number ')
num = int(num)
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
update: thanks to Vova the code is now working.
fixed code:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
It will print 0 each time when you type 1 numeric number(0..9)
When you type more than 1 numeric not mirror number for example 2,3,4 etc(10,234 etc), it will print 1
Moreover it will never print True, coz you exit() it in if statement
Try to input 23, it will print 1:
num = int(input('please enter your number '))
count = 0
for i in range(1, 500):
if str(num) == str(num)[::-1]:
print(count)
exit()
else:
num = num + int(str(num)[::-1])
count += 1
print('True')
I'm a beginning programmer in python and have a question about my code I'm writing:
number = int(input("Enter a random number: "))
for num in range(1, number + 1) :
for i in range(2, num) :
if (num % i) == 0 :
break
else :
print(num)
break
When I run this program I also get 9, 15 21 as output. But these are not prime numbers.
What is wrong with my code?
Thanks!
With if (num % i) == 0: you go to the else block for every num, which is not a multiply of 2, as you start i with 2, thus printing num. I got all odd numbers printed with your code.
You can use something like this:
number = int(input("Enter a random number: "))
for num in range(1, number + 1):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num)
It sets prime to False when it encounters a divisor without rest.
the trouble is in your else: statement which has to run outside of the first loop. I recommend the following:
def isprime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
for num in range(1, number + 1) :
if isprime(num):
print num
Your problem
The else statement that you put inside the for loop means that if that number(num) is divisible by this current no represented by i, return true considering it as a prime which IS NOT CORRECT.
Suggestion
Your outer loop starts with 1 which should change to 2, as 1 is not a prime number
Solution
def fun(number):
#Not counting 1 in the sequence as its not prime
for num in range(2, number + 1) :
isPrime = True
for i in range(2, num) :
if (num % i) == 0 :
isPrime = False
break
if isPrime:
print num
fun(10)
Output
1
2
3
5
7
I am assuming the random number is the range you want the numbers to be within.
I found that the variable i is always equal to 2 in your code.This destroys the purpose of having a second for loop
Prime numbers are numbers that cannot be divisible by 2, 3 or 7, excluding 2, 3 or 7!
With this knowledge I adapted your code to show the true prime numbers.
solution
number = int(input("Enter a random number: "))
for num in range(2,number +1) :
printnum = True
if num == 2:
printnum = True
elif num == 3:
printnum = True
elif num == 7:
printnum = True
elif num % 2 == 0:
printnum = False
elif num % 3 == 0:
printnum = False
elif num % 7 == 0:
printnum = False
if printnum == True:
print(num)
This is my method to generate first ten prime numbers with no imports, just simple code with components we are learning on college. I save those numbers into list.
def main():
listaPrim = []
broj = 0
while len(listaPrim) != 10:
broj+= 1
brojac = 0
for i in range(1,100):
if broj % i == 0:
brojac += 1
if brojac == 2:
listaPrim.append(broj)
print(listaPrim)
if __name__=='__main__':
main()
Problem
Here is the problem I am trying to solve.
The prime factors of 13195 are 5, 7, 13, 29. What is the largest prime factor of the number 600851475143?
def prime_calc():
num = raw_input("What is the number you want the primes for?")
prim_num = []
x = 2
while num/x > 1:
new_num = num / x
if num % x == 0:
return prim_num.append(x)
elif num % x != 0:
new_num = num/x += 1
return prim_num.append(x)
else:
break
I keep getting an invalid syntax error starting from the bottom up to the fourth line that doesnt like my "+=" operator
This line:
new_num = num/x += 1
should be broken into two lines:
x += 1
new_num = num/x
The statement x += 1 in python doesn't return anything, so you can't use it as part of an expression.
Similarly, the two instances of:
return prim_num.append(x)
Also won't work, since the statement: prime_num.append(x) doesn't return anything.
You need to break this into:
prime_num.append(x)
return prime_num
num=int(input("Please enter number to calculate prime factor"))
k=0
item=[]
if(num%2==0):
prime=2
item.insert(k,prime)
k=k+1
j=3
flag=int(num/2)
while(j<flag and num>2):
if num%j==0:
prime=j
item.insert(k,prime)
k=k+1
num=num/j
j=j+2
else:
j=j+2
if k==0:
print("sorry no prime factor for this number")
else:
print("Please find the largest prime factor below")
print(item.pop())