I need to test whether n is a multiple of 2 and then divide the number by 2. If the number isn't a multiple of 2, then I have to do 3*n+2.
How do I make it loop so I can get the following: 12, 6, 3, 10, 5, 16, 8, 4, 2, 1?
Here's my current code:
n=12
while n!=0:
if n%2==0:
print (n)
n=n/2
if n!=n%2:
if n !=1:
n = 3*n+2
else:
break
print(n)
First note is that it is 3*n+1, second one is that you have to write n=n/2 in your first if.
Overall this code is what you want:
n = 12
while n != 0:
if n % 2 == 0:
print(n, end=' ')
n = n / 2
elif n % 2 != 0:
if n != 1:
print(n, end=' ')
n = 3 * n + 1
else:
print(1)
break
Or this:
n = 12
while n > 1:
if n % 2 == 0:
print(n, end=' ')
n = n / 2
elif n % 2 != 0:
if n != 1:
print(n, end=' ')
n = 3 * n + 1
else:
print(1)
Good luck
First of all your formula of 3*n + 2 will lead to infinite loop. According your sample output, it needs to be 3*n + 1.
n = 12
while n >= 1:
print(n, end=' ')
if n == 1:
break
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
Related
b = input().split(' ')
c = list(map(int,b))
y = 0
for i in range(len(b)):
if c[i] %2 == 0:
print(c[i])
y = 1
elif i == len(c) - 1 & y == 0:
print('No number that is divisible by 2')
Code takes a list of numbers as input, then it prints all values divisible by 2, but if there are no such values it should print about this only once. My code works properly only in certain cases. I know another implementation but i need solution within 1 loop
Add break:
b = input().split(' ')
c = list(map(int,b))
y = 0
for i in range(len(b)):
if c[i] %2 == 0:
print(c[i])
y = 1
elif i == len(c) - 1 & y == 0:
print('No number that is divisible by 2')
break
You may want to simplify by calculating the numbers divisible by 2 first, then deciding what to print:
nums = map(int, input().split(' '))
div2 = [i for i in nums if not i % 2]
if div2:
for i in div2:
print(i)
else:
print('No number that is divisible by 2')
print("Number of primes must be greater than 2")
number = int(input("Number of primes: "))
if number < 1:
print("Invalid input")
exit()
print(2)
print(3)
i = 0
no_primes = 2
while 1 < 2:
m = 6 * i - 1
n = 6 * i + 1
if (2 ** m) % m == 2:
print(m)
no_primes += 1
if no_primes == number:
break
if (2 ** n) % n == 2:
print(n)
no_primes += 1
if no_primes == number:
break
i += 1
My code uses the fact that primes can be expressed in the form 6n-1 or 6n+1 except for 2 and 3. My while loop looks quite strange but I don't have the expertise to manoeuvre with loops consisting of two variables (no_primes and i in this case). When I generate the first 1000 primes, it skips a few, ending with 7789 instead of 7919. Does anybody know why? Also, sorry if the code looks redundant. If it is, please do state how I can improve it
I started python only a few weeks ago, thought you'll should know
I'm not sure checking (2 ** m) % m == 2 and (2 ** n) % n == 2 will give you all prime numbers.
Have you compared with a more brute force approach?
print("Number of primes must be greater than 2")
number = int(input("Number of primes: "))
if number < 1:
print("Invalid input")
exit()
elif number == 1:
print(2)
else:
print(2)
print(3)
prime_set = {2,3}
i = 1
while len(prime_set) < number:
m = 6 * i - 1
n = 6 * i + 1
if all(m % p != 0 for p in prime_set):
prime_set.add(m)
print(m)
if all(n % p != 0 for p in prime_set):
prime_set.add(n)
print(n)
i+=1
Here the solution edited by #Aqeel for improved Efficiency:
import time
import math
number = int(input("Number of primes: "))
t_0 = time.time()
if number < 1:
print("Invalid input")
exit()
elif number == 1:
print(2)
else:
print(2)
print(3)
primes = [2, 3]
i = 1
while len(primes) < number:
prime_m = True
prime_n = True
m = 6 * i - 1
n = 6 * i + 1
sqrt_m = math.sqrt(m)
sqrt_n = math.sqrt(n)
for prime in primes:
if prime > sqrt_m:
break
if m % prime == 0:
prime_m = False
break
if prime_m:
print(m)
primes.append(m)
if len(primes) == number:
break
for prime in primes:
if prime > sqrt_n:
break
if n % prime == 0:
prime_n = False
break
if prime_n:
print(n)
primes.append(n)
i += 1
t_1 = time.time()
print(f"Found %s prime numbers in %ss" % (number, t_1 - t_0))
The answer to your issue is that you are printing non-prime numbers.
Running your code (with input 1000) provides 1000 numbers, but checking these numbers with a proper is_prime() function yields these numbers that are not primes:
341
1105
1387
1729
2047
2465
2701
2821
3277
4033
4369
4681
5461
6601
As answered by #Tranbi, (2 ** m) % m == 2 is not a proper test for testing primes. Check out this answer for a better solution
How do I include the user input value in the very first place in the output?
here is my code below:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)
So when I entered 6, it was printed like this:
3 10 5 16 8 4 2 1
My entered value (which MUST be included) is missing.
Please help!
In your current code, you add n to seq at the end of every iteration. To add the initial value of n, simply do seq.append(n) before entering the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
seq.append(n) # this is the addition you need
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)
There are several ways you can do this. I believe the most logical way is to move your seq.append(n) statement to the first line of your while loop to capture your input. The issue will then be that 1 will be dropped off the end of the list. To fix that, you change your while loop condition to capture the one and add a condition to break out of the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 0):
seq.append(n)
if n == 1:
break
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print()
print(*seq)
#output:
Enter a number (greater than 1): 6
6 3 10 5 16 8 4 2 1
I am making a program in python that finds the probability of getting a prime number (E) when n = any number from 0 - 200,000. E = n^2+n+5. However, the "while true, break" cycle doesn't work when t = 200,000. Here is my code:
#import time
#Does E = n^2 + n + 5 always produce prime numbers?
n = 0
t = 0
p = 0
while 3 > 2:
n2 = n*n
E = n2 + n + 5
n = n + 1
if E > 1:
for i in range(2, E):
if((E % i) == 0):
print(E, "is not prime.")
#time.sleep(3)
else:
print("Found a prime number!", E)
#time.sleep(3)
p = p + 1
t = t + 1
if(t >= 200000):
break
fraction = p/t
percent_int = fraction*100
percent = int(percent_int)
print("The probability of getting a prime number is:", percent)
Change this line:
if(t >= 200000):
To:
if(t > 200000):
It just take to long because you run for i in range(2, E): inside while loop.
put print(t) inside while loop to observe progress of program to get idea how long it will take.
Changing your code to this:
n = 0
t = 0
p = 0
while 3 > 2:
n2 = n*n
E = n2 + n + 5
n = n + 1
if E > 1:
for i in range(2, E):
if((E % i) == 0):
pass
else:
print("Found a prime number!", E)
p = p + 1
t = t + 1
print(t)
if(t >= 200000):
break
fraction = p/t
percent_int = fraction*100
percent = int(percent_int)
print("The probability of getting a prime number is:", percent)
and letting it run shows that t is only incremented every time a prime number is found.
You might want to break elsewhere, perhaps set t to 500
I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime...
Any assistant will be most appreciated !
def primes():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
num = 0
i = 0
ctr = 0
for num in range(start,end+1,1):
ctr = 0
for i in range(2,num//2,1):
if num % i == 0 :
ctr = ctr + 1
break
if (ctr==0 and num != 1):
print(num)
for i in range(2,num//2,1):
Lets check this snippet of code when num = 4,it becomes
for i in range(2,2,1):
Now we see the problem.
Solution..?
for i in range(2,(num//2)+1,1):
The following methods are all possible prime checkers you might use to check within your range:
def isPrime(Number): # slow
return 2 in [Number, 2 ** Number % Number]
def isprime(n): # out of memory errors with big numbers
"""check if integer n is a prime"""
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True
def is_prime(n): # Best until now
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(n ** 0.5)
f = 5
while f <= r:
# print '\t', f
if n % f == 0:
return False
if n % (f + 2) == 0:
return False
f += 6
return True
for i in range(2,num//2,1):
Above line is wrong. You are iterating from 2 to num / 2 - 1.
You should iterate from 2 to sqrt(num). (range(2, int(math.sqrt(n)) + 1))
Alternatively you can do a special check for 2 and modify your range to range(3, int(math.sqrt(n) + 1, 2)