count divisors problem in python using while - python

i try to count divisor if number have 4 divisors will print "elegant number" else "not elegant number" but i have trouble while print it i have finished to show divisors from number but my program can't show elegant number or not. i have your opinion to fixed it. here my code:
N = int(input("enter number: "))
i = 1
factor = 0 # this for count divisors but doesn't right
while (i <= N):
if(N%i==0):
print(i)
factor+=i # this for count divisors but doesn't right
i+=1
if(factor==4):
print("elegant number")
else:
print("not elegant number")
i have put comment in line which line for count divisors.

I think the main issue inside the code was adding factor += i instead of factor += 1 (to account for a new divisor).
Also, the placement of the factor += 1 condition had to be inside the if-statement.
Here is an updated version of the code:
N = int(input("enter number: "))
factors = 0
for i in range(1,N+1): # Add N+1 to loop over "i=N" as well
if N%i == 0:
print(i)
factors += 1
if factors == 4 :
print("elegant number")
else:
print("not elegant number")
Please let me know in the comments section if you need further help. Cheers,
PS. Alternative version using a while-loop:
N = int(input("enter number: "))
factors = 0
i = 1
while i<=N:
if N%i == 0:
print(i)
factors += 1
i += 1
if factors == 4 :
print("elegant number")
else:
print("not elegant number")

Related

Write a python script to print all Prime numbers between two given numbers (both values inclusive)

Write a python script to print all Prime numbers between two given numbers (both values inclusive)
can anyone please tell what am I doing wrong here ?
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
for i in range(2,k):
if k%i!=0:
if k!=i:
continue
elif k==i:
print(k)
break
elif k!=i:
break
you are checking if a number is prime the wrong way there are many
unhandled cases in your code for example if a is larger than b
you will start looping from "a" anyway
and even if the values are sat up correctly the algorithm is not right
here is my optimal solution hope it will help
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
def is_prime(n):
# negative numbers cannot be primes 1 and 0 are also not primes
if n <= 1:
return False
# since 2 is the first prime we will start looping from it
# until n since you mentioned that n is included
for i in range(2, n + 1):
# if n is cleanly divisible by any number less than n
# that means that n is not prime
if n % i == 0 and n != i:
return False
return True
for k in range(a,b):
if a > b:
print ("a cannot be bigger than b")
if is_prime(k):
print(k)
Here's the solution. I added some comments to explain what the code does.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
# Include b in the range by adding 1
for num in range(a, b + 1):
# Prime numbers are greater than 1
if num > 1:
for i in range(2, num):
# If the number is divisible, it is not prime
if num % i == 0:
# Check if the number is equal to the number itself
if num != i:
break
else:
# If the loop was not broken, the number isn't divisible
# by other numbers except itself and 1, so it's prime
print(num)
Well, a prime is "a number that is divisible only by itself and 1", so to actually first I would go only to range(2, k-1). This approach you have is one of the most straightforward ways of doing it, and is not computationally friendly. There are algorithms that specialize in this kind of prime number finding.
I have fixed the code, simplifying the expressions and adding like already mentioned +1 for inclusivity.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b+1):
for i in range(2,k+1):
if k==i:
print(k)
elif k%i!=0:
continue
else: # is divisible and isn't 1 or the number
break
I encourage you to see this post, how they do it.
An other way of doing it would be:
#Check only 1 number at time:
def check_prime(check):
if check > 1:
for i in range(2, check):
if check % i == 0:
return False
return True
return False
#then check your numbers in a loop
list_prime = []
for i in range(50, 250):
if check_prime(i):
list_prime.append(i)
print(list_prime)
That way you can check 1 possible prime number at time.
If you need numbers in between just put it in loop.
Usually, when generating prime numbers utilizing some form of the "Sieve of Erotosthenes" algorithm, it is only necessary to check for denominator values up to the square root of the number being evaluated. With that in mind, here is one more possible take on your prime number loop test.
import math
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
if k == 2 or k == 3: # Pick up the prime numbers whose square root value is less than 2
print(k)
x = int(math.sqrt(k) + 1) # Need only check up to the square root of your test number
for i in range(2,x):
if k%i!=0:
if x-1 > i:
continue
else:
print(k)
else: # If the remainder is zero, this is not a prime number
break
Another version to try.

How do I get Python to print from 1 to user input?

I'm trying to solve the scenario with these conditions:
Ask the user to enter a number
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number. If it is an even number, do not display the number.
If the user enters a number that is 0 or less, display error
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
Your solution will be :
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run. I hope you understand.
You have to check the condition num <= 0 as soon as the user enters the number:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)

Enter n different positive numbers. Calculate the average value of all prime numbers among them. [Python]

I need to do as the title suggests however I have ran into a problem. This is my code so far:
#Input
n = int(input('Enter n: '))
#Prime = 0
p = []
#Loopidty
for i in range(n):
#Ask user to input x
x = int(input('Enter a Number: '))
#Check if prime
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
p.append(x)
#Answer
Answer = sum(p) / n
print('The answer is: ', Answer)
The issues is when I add the prime numbers to the list it only adds the first number and stops there, how do I combat this?
Many thanks
It's a good idea to break your code into smaller parts. We can create a function to check if a number is prime or not and check that it is correct. After that just add the rest of the code.
import math
def is_prime(x):
"""Check that a number `x``is prime"""
# You only need to go up to sqrt(x)
for n in range(2, int(math.sqrt(x) + 1)):
if x % n == 0:
return False
return True
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sum = 0.0
num_entries = 0 # Number of prime numbers entered by the user
n = int(input('Enter n: '))
for i in range(n):
x = int(input('Enter a Number: '))
if is_prime(x):
sum += x
num_entries += 1
if num_entries == 0:
print("You didn't enter any prime number")
else:
print("The average of the entered prime numbers is ", sum / num_entries)

How do I store information in lists

My goal is to create a program that checks whether a number is a prime number and displays the total number of factors if it is not a prime number.
I have started the code but I realize I need to store my factors in a list in order for the number of factors to be displayed. Here is my (edited) Python code so far:
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
for x in range(1, userNum+1):
if(userNum % x == 0):
factor = 0
numFactors.append(x)
factor = factor + 1
print(userNum,"is not a prime number")
print("Number of factors: ", factor)
break
else:
print(userNum,"is a prime number")
Can someone please tell me how to continue with storing factors into my list (numFactors)? Thank You!
You need to use append()
Your syntax changed as below.
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
for x in range(1, userNum+1):
if(userNum % x == 0):
factor = 0
numFactors.append(x)
factor = factor + 1
...
...
But there is a logical flaw in your code. Try input as 99.
Corrected solution
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
# A prime number (or prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
# Hence range starting from 2
for x in range(2, userNum+1):
if(userNum % x == 0):
numFactors.append(x)
if len(numFactors) == 1:
print(userNum, " is a prime number")
else:
print(userNum,"is not a prime number")
print("Number of factors: ", len(numFactors))
print("Factors : ", numFactors)
Output
Enter a number: 99
User Number: 99
99 is not a prime number
Number of factors: 5
Factors : [3, 9, 11, 33, 99]
First, you need to put the line that defines numFactors, numFactors = [], outside of and before the for loop. Otherwise, it will be continually set to an empty list for each iteration of the loop.
Values can be added to the end of a list by using the list's append method. For example, numFactors.append(2) would add 2 to the end of the list.
Your mistake is lacking check whether x is equal to userNum, that is in the end of the loop.
My other suggestion is you remove variable factor as this can be known from the length of the numFactors list.
userNum = int(input("Enter a number: "))
print("User Number: ", userNum)
numFactors = []
for x in range(1, userNum + 1):
if userNum % x == 0:
numFactors.append(x)
if userNum == x:
print("Factors: " + str(numFactors))
if len(numFactors) == 2:
print(userNum, "is a prime number")
else:
print(userNum, "is not a prime number")
print("Number of factors: ", len(numFactors))

How do you find the first N prime numbers in python?

I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.

Categories