fixing Fibonacci numbers from a range of 1 to 50 Python - python

I have a set of numbers from 1 to 50 and from these numbers I have to find which are Fibonacci number, after that I have to find which of these numbers contain the number 1 and 2.
For example in my code my Fibonacci numbers are 0, 1, 2, 3, 5, 8, 13, 21, 34 I have written a code, but I can't add the last part of the question, so it finds out which of these numbers contain a number 1 or 2 in them.
here is my code
def isPerfectSquare(x):
s = int(math.sqrt(x))
return s * s == x
def isFibonacci(n):
return isPerfectSquare(5 * n * n + 4) or isPerfectSquare(5 * n * n - 4)
for i in range(0, 51):
if isFibonacci(i) == True:
print(i, "is a Fibonacci Number")
else:
print(i, "is a not Fibonacci Number ")
for q in range(1, 51):
if isFibonacci(i) == True and '1' in i and '2' in i:
print(q)
else:
print('Error')
the result is something like this is gives me all of these numbers 0, 1, 2, 3, 5, 8, 13, 21, 34 as Fibonacci and the rest are not which is perfect but then it keeps giving me error, what i wanted to do is it to write a loop that contains all Fibonacci numbers like these 0, 1, 2, 3, 5, 8, 13, 21, 34 and that contain a 1 and 2 in the number to be printed out but it just prints everything as Error.

for q in range(1, 51):
if isFibonacci(q) == True and '1' in str(q) and '2' in str(q):
print(q)
else:
print('Error')
This loop's variable is q, not i.
You have to convert the number to string using str(...).

Related

Python printing many times over for single print

My code is:
for n in range(1,10000000):
if n>1:
for i in range(2,n):
if n % i == 0:
break
else:
v = 2+n
for i in range(2,v):
if v % i == 0:
break
else:
print(n,v)
When I run the code, it prints multiple of each number with each having a random number of the particular two numbers. I am having trouble fixing the code. I have asked others who are more well-versed in coding than I am, but they were unable to solve the problem. Help would be greatly appreciated. Thank you!
The output is not random, but as the desired output is not defined, I'll start with explaining what the current algorithm actually does;
The code can be split in to two main functionalities. The first functionality looks for a prime number n. If n is not prime, the code continues to the next n:
for n in range(1,10000000):
if n>1:
for i in range(2,n):
if n % i == 0:
break
The second functionality comes into play only if n is prime (a clever use of for..else). It will now check to see if n+2 is divisible by any number from 2 up to n+1. I took the liberty of replacing v with n+2 in the following snippet, as I believe it makes things a bit clearer;
else:
#v = 2+n # taking liberty..
for i in range(2, n+2):
if (n+2) % i == 0:
break
else:
print(n, n+2)
To illustrate what actually happens, I chose primes 5, 7, 11, and 23, as I believe these four can explain the output pretty well. Starting with 5:
for i in range(2, 7): # i -> [2, 3, 4, 5, 6]
if (7) % i == 0:
break
else:
print(5, 7)
In the snippet above, 5 7 will be printed 5 times, once for each i in the loop, as 7 is a prime and is not divisible by any given i.
for i in range(2, 9): # i -> [2, 3, 4, 5, 6, 7, 8]
if (9) % i == 0:
break
else:
print(7, 9)
Here you will find that 7 9 is only printed once, because 9 is not divisible by 2, but it is divisible by 3 - in which case, the loop breaks, and continues to the next prime n. Now let's look at n=11:
for i in range(2, 13): # i -> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
if (13) % i == 0:
break
else:
print(11, 13)
Here, like with n=5, n+2 is also prime (13). As it is not divisible by any number in i, the sequence 11 13 will be printed the length of i, which is 11 (it will always be n, as we start from 2, and add 2 to n).
for i in range(2, 25): # i -> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
if (25) % i == 0:
break
else:
print(23, 25)
This is the first interesting case in the realm of lower numbers. Up to 23, all n+2 were either prime, or divisible by 3; they were printed n times, or just once. With n=23, the sequence 23 25 is printed 3 times, because 25 is not divisible by 2, 3, or 4 (3 prints), but it is divisible by 5, so now the loop breaks again, and continues to the next prime n.
Again, the resulting output you are looking for is not clear, but reading through previous comments I have to warn - this solution will not print two prime numbers separated by 2 (as #alani figured), it will simply ensure each line is printed just once:
for n in range(3,10000000):
for i in range(2,n):
if n % i == 0:
break
else:
v = 2+n
for i in range(3,v):
if v % i:
print(n,v)
break
I made it so it'll only print once each time, along with only going to the square root of each number as going past that is overkill
for n in range(2,10000000): #started at 2 instead of 1
#removed if statement because i changed start from 1 to 2
for i in range(2,int(n**0.5) + 2): #now goes to square root plus 1(to correct for automatic rounding down)
if n % i == 0:
break
else:
v = n + 2
for f in range(2,int(v**0.5) + 2): #now goes to square root plus 1(to correct for automatic rounding down)
if v % f == 0:
break
elif f == int(v**0.5) + 1: #changed else to elif with condition of being at last iterated integer
print(n,v)
I didn't want to totally revamp your code but if you do want to make this more efficient, i would recommend creating a list of prime numbers you find(by appending each time you find one) and then using a for loop iterating over the list up to the square root of the current value(as iterating over composite numbers is inefficient, since they are multiples of the prime numbers)
Hopefully this is what you wanted, if not i can try to help further though, also please don't take my recommendation as criticism or anything, it's just my opinion on what might make your code run faster

Python coding using collatz conjecture

I am new at coding and i am trying to do a collatz conjecture.
I think i already made it by i cant code a way to count how much "steps" it takes to the 1.
This is the code i already did.
n = int(input("Enter a number!"))
def lothar(n):
print(n)
if n == 1:
return i
if n % 2 == 0:
n = n / 2
else:
n = ((n*3) + 1)
return lothar(n)
print(lothar(n))
I want to count using a while structure.
For example: in number 4 , it takes 3 steps.
4
2
1.
There's a few ways to count the steps, but I've gone with removing the recursion and using a loop instead:
n = int(input("Enter a number: "))
def lothar(n):
steps = [n]
while n > 1:
if n % 2 == 0:
n = n // 2
else:
n = ((n*3) + 1)
steps.append(n)
return steps
sequence = lothar(n)
print(sequence)
print(str(len(sequence)-1) + " step(s)")
That will return the sequence, which then means we can display the sequence and also output the amount of steps (i.e. the length of the sequence minus one).
For example:
Enter a number: 9
[9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
19 step(s)
Put the while loop into the function, and give a count variable for counting.
n = int(input("Enter a number!"))
count = 1
def lothar(n,count):
while n != 1:
if n % 2 == 0:
count += 1
n = n / 2
else:
count += 1
n = ((n*3) + 1)
return count
print(lothar(n,count))
Because the result you want is to include 4, count will be added one more time, but if you want to count the number of loops, you should set count to 0 for calculation.

How to make a program which prints prime numbers in given range

I want to make a program as an exercise which prints all prime numbers in range of given limit(parameter). Thanks.
#prime numbers
prime = list()
for x in range(1, 100):
for a in range(2, x):
if x % a == 0:
break
else:
prime.append(x)
print(prime)
You can use this list comprehension to find prime numbers in given range;
def prime_generator(number):
return [x for x in range(2, number) if not any(x % y == 0 for y in range(2, int(x/2)+1))]
In: prime_generator(30)
Out: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Prime numbers that are factors of a received integer

I've been trying to complete this assignment but I couldn't get what is asked, which is: in Python 3, Ask a user to enter an integer (1, 1000). Out of the list of the first prime numbers 2,3,5,7, print those prime numbers that are factors of the received integer.
I hope could help me to get this.
def get_primes(n):
out = list()
sieve = [True] * (n+1)
for p in range(2, n+1):
if (sieve[p]):
out.append(p)
for i in range(p, n+1, p):
sieve[i] = False
return out
def get_factors(n):
output = list()
for i in range(1, n + 1):
if n % i == 0:
output.append(i)
return output
# input_number = input('Enter a number')
# input_number = int(input_number)
input_number = 30
primes = get_primes(input_number+1) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
factors = get_factors(input_number) # [1, 2, 3, 5, 6, 10, 15, 30]
prime_factors = list()
for i in factors:
if i in primes:
prime_factors.append(i)
print(prime_factors)
Output:
[2, 3, 5]
Code for getting prime numbers:
Print series of prime numbers in python

Fibonacci sequence using codelab

In the following sequence, each number (except the first two) is the sum of the previous two number: 0, 1, 1, 2, 3, 5, 8, 13, .... This sequence is known as the Fibonacci sequence.
Given the positive integers m and n (with m < n) create a list consisting of the portion of the Fibonacci sequence greater than or equal to m and less than or equal to n. For example, if m is 3 and n is 6, then the list would be [3, 5] and if m is 2 and n is 20, then the list would be [2, 3, 5, 8, 13].
Associate the list with the variable fib.
Have done this far, but still getting error.
Where does it need to be fixed?
fib = [0,1,1]
result = 0
while result <=n:
result=fib[-1]+fib[-2]
if result <=n and result>=m:
fib.append(result)
# create a fibonacci series from 0 to n
f = [0,1]
for i in range(1, n+1):
x = f[i]+f[i-1]
if x > n:
break
else:
f.append(x)
# copy only those numbers of series that are in range m to n
fib = []
for i in range(0, len(f)):
if f[i] >= m and f[i] <= n:
fib.append(f[i])
You could use the code below.
fib = [0,1,1]
fibrange = [] # keeps your digits that are in range m < n
result = 0
n = 80
m = 2
while result <=n:
result =fib[-1]+fib[-2]
fib.append(result)
if result <=n and result>=m:
fibrange.append(result)
print fibrange
fib=[0,1]
i=0
while i <=n:
i=fib[-1]+fib[-2]
if i<=n:
fib.append(i)

Categories

Resources