This is the description of the given problem:
If 1 plus 2 elevated to num is exactly divisible by 1 plus 2 multiplied by num, then num is a Curzon number.
Given a non-negative integer num, implement a function that returns True if num is a Curzon number, or False otherwise.
The code I wrote was:
def is_curzon(num):
curr = 0
mult_add = 2 * num + 1
while curr <= num:
if (2**curr + 1) % mult_add == 0:
return True
curr += 1
return False
It's not passing the test for when is_curzon(120) where the answer is supposed to be False but I'm getting True.
The obvious answer would be the following and it gives the correct answer for is_curzon(120):
def is_curzon(num):
return not (2**num + 1) % (2*num + 1)
But I wanted to lessen the amount of time the program has to run to solve this problem. If num is a very big number, I don't want to overwhelm the program.
Could you help me on how I can fix this bug?
return not (2**num + 1) % (2*num + 1)
is a statement, which takes less time than a loop, that has to run over and over again:
while curr <= num:
curr+=1
has to repeat "num" +1 times because the condition gets false when "curr" gets bigger than num.
(This is a shortened version, in your code if (2**curr + 1) % mult_add == 0 gets checked first, and returns True if that is the case, else it increases curr by +=1)
if you still want to find the problem in your code, first try to solve it by tracing back what is happening, you can trace it yourself or maybe try to run your code through : http://pythontutor.com/visualize.html#mode=display and see what happens.
I am working on a collatz sequence that i have found in a book and i want to input the number but it dosen t work , when i put the number the enter keybord key does not work , have i made something wrong in my program ? :
even = range(0,10**5,2)
odd = range(1,10**5,2)
def collatz_s(num):
while num !=1 :
if num in even :
result = num /2
print(result)
num = result
elif num is odd :
result = num *3+1
num = result
print(result)
num = int(input('choose a random number'))
collatz_s(num)
To check whether a number is odd or even, rather than generating range objects and checking whether a number is in them, look at the remainder in the division by two, which you can get with num % 2. If the remained is 1, it means the number is even. Otherwise, it's odd.
Also, use num // 2 to perform an integer division. That way dividing 16 by 2 will give you 8 (the integer number), instead of 8.0 (the floating point number.) It turns out this is really important here, especially since you're interested in finding the remainder of the division (a concept mainly concerning integer numbers.)
I believe it's quite possible that a rounding error in the floating point division might have put your program into an infinite loop (since a number with a tiny decimal part would not be in either even or odd range.) Or if you were surpassing the limit of your ranges (105) you'd be in the same situation where neither branch matches. Using integer division and checking for even or odd using the remainder should fix both issues.
def collatz_s(num):
while num != 1:
if num % 2 == 0:
num = num // 2
print(num)
else:
num = num * 3 + 1
print(num)
The problem is within your elif block, here elif num is odd : change is to in when dealing with remainder use integer division(//) instead to avoid precision error .
def collatz_s(num):
while num != 1:
if num in even:
result = num // 2
print(result)
num = result
elif num in odd:
result = num * 3 + 1
print(result)
num = result
num = int(input('choose a random number'))
collatz_s(num)
# input 5
# output
16
8
4
2
1
I am a new person to programming and still wrapping my head around the logic. The code I am laying out for you works: it produces the first N prime numbers. i.e. if user enters 10, the code will produce all primes up to and including 10. This was an assignment question, by the way. This is how my professor laid it out.
Also, if I am not displaying my code correctly, please give me some helpful hints about how to do that. I don't know what a fence is, but I indented each line 4 spaces, if that helps.
I stepped through this code in debug mode, and noticed that the value of j never went beyond 2 or 3. Why not?
n = int(input("Please enter the number up to which you want to find prime
numbers: "))
count = 0
if n > 1:
for i in range(2, n + 1):
isPrime = True # set flag to True
for j in range(2, i // 2 + 1):
if i % j == 0:
isPrime = False
break
if isPrime:
print(i, "is a prime number.")
count += 1
else:
print("Prime numbers must be greater than 1.")
print(count, "prime numbers have been found.")
There were no error messages that I could detect.
I've recently started learning Python. My apologies if this is really obvious.
I am following along with the 2008 MIT open course on Computer Science and am working on the problem of calculating the 1000th prime integer. Python 2.7.3, Win7 lappy (cough, cough...)
Here's the code I came up with:
num = 3
primeList = [2]
while len(primeList) < 1000:
for i in primeList:
if num % i == 0:
break
else:
primeList.append(num)
num += 1
print "The 1,000th PRIME integer is", primeList[999]
One of the assignment conditions was to only check odd numbers. Given the starting num is three, I figured it would be easy enough to simply change num+=1 to num+=2. Of note: I won't bore you with the detailed code I composed, but while writing this I was using a very verbose mode of printing out the results of each check, whether or not it was prime, which number was being checked, which integer divided into it if it wasn't prime & such (again, sorry - newB!)
At this point I became curious to test if this was actually taking less time to compute - seemed like if half the numbers are being checked for primacy, it should take half the time, no?
I imported the time module to check how long this was taking. Computing to the 1000th was pretty quick either way so I increased the number of primes I was searching for to the 10,000th and didn't see any significant difference. between num+=1 & num+=2
import time
start = time.time()
num = 3
primeList = [2]
while len(primeList) < 10000:
for i in primeList:
if num % i == 0:
break
else:
primeList.append(num)
num += 2
print "The 10,000th PRIME integer is", primeList[9999]
end = time.time()
print "That took %.3f seconds" % (end-start)
Sometimes the n+=2 even took a couple milliseconds longer. ?. I thought this was odd and was wondering if someone could help me understand why - or, more to the point: how?
Furthermore, I next imported the sqrt() function thinking this would reduce the number of integers being checked before confirming primacy, but this doubled the runtime =^O.
import time
start = time.time()
from math import sqrt
num = 3
primeList = [2]
while len(primeList) < 100000:
for i in primeList:
if i <= sqrt(num):
if num % i == 0:
break
else:
primeList.append(num)
num += 2
print "The 100,000th PRIME integer is",primeList[99999]
end = time.time()
print 'that took', end - start, "seconds, or", (end-start)/60, "minutes"
Certainly - it might be the way I've written my code! If not, I'm curious what exactly I am invoking here that is taking so long?
Thank you!
Two things.
First, you're calculating sqrt(n) on every loop iteration. This will add work, because it's something else your code now has to do on every pass through the loop.
Second, the way you're using sqrt doesn't reduce the number of numbers it checks, because you don't exit the loop even when i is bigger than sqrt(n). So it keeps doing a do-nothing loop for all the higher numbers.
Try this instead:
while len(primeList) < 100000:
rootN = sqrt(num)
for i in primeList:
if i <= rootN:
if num % i == 0:
break
else:
primeList.append(num)
break
else:
primeList.append(num)
num += 2
This finds 100,000 primes in about 3 seconds on my machine.
I've made a program which takes number of test cases as input and for each test case, it needs a number as input. Finally it checks whether the numbers you have entered are fibonacci numbers or not and prints accordingly. I've had no problems running it on my PC.But when i upload it to CodeChef.com(where i saw this quesion), it shows runtime error.
Any help is appreciated and as i'm a noob my code might look lengthy ., any modifications are welcome.Thanks!
Here's my code:
def isperfect(n):
import math
if n < 0:
print("No Solution")
return False
else:
test = int(math.sqrt(n))
return test*test == n
test_cases = int(input())
count = 0
store = []
while count < test_cases:
x = int(input())
store.append(x)
count += 1
for each_item in store:
assert isinstance(each_item, int)
s1 = 5*each_item*each_item-4
s2 = 5*each_item*each_item+4
if(isperfect(s1) == True or isperfect(s2) == True):
print("YES")
else:
print("NO")
This is the most elegant solution i've encountered:
def is_fibonacci(n):
phi = 0.5 + 0.5 * math.sqrt(5.0)
a = phi * n
return n == 0 or abs(round(a) - a) < 1.0 / n
The code is not mine, was posted by #sven-marnach.
The original post:
check-input-that-belong-to-fibonacci-numbers-in-python
The runtime error is apparently due to an exception, but Codechef does not provide any more information. It could be various things including divide by zero, memory exhaustion, assertion failure, ...
Although your program works for many common numbers, it doesn't handle all the inputs that the Codechef constraints allow. In particular, the number to be tested can have up to 1000 digits in it. If you try a large input like a 1000-digit number, you'll find it fails. First it fails because of your assert isinstance(each_item, int); a number of 12 digits or more is not of type int. You can just remove the assertion. The next failure occurs because you are using the floating point sqrt routine, and that requires the integer to be converted into floating point. Python can handle very long integers, but the floating point representation is more limited in its precision, and cannot handle 1000 digit integer conversions. That's harder to fix, but can be done. See this ActiveState recipe for an all-integer solution for square root.
I've figured that this can be done by using Newton- Raphson method, i have replaced the code in the function isperfect() with Newton-Raphson formula code, removed assertion and it worked. Thanks for all your help.
Here's the final code:
def isperfect(n):
x = n
y = (x + n // x) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x*x == n
test_cases = int(input())
count = 0
store = []
while count < test_cases:
x = int(input())
store.append(x)
count += 1
for each_item in store:
s1 = 5*each_item*each_item-4
s2 = 5*each_item*each_item+4
if(isperfect(s1) == True or isperfect(s2) == True):
print("YES")
else:
print("NO")
This is going to be a very efficient way of doing it.
In [65]:
import scipy.optimize as so
from numpy import *
In [66]:
def fib(n):
s5=sqrt(5.)
return sqrt(0.2)*(((1+s5)/2.)**n-((1-s5)/2.)**n)
def apx_fib(n):
s5=sqrt(5.)
return sqrt(0.2)*(0.5*(1+s5))**n
def solve_fib(f):
_f=lambda x, y: (apx_fib(x)-y)**2
return so.fmin_slsqp(_f,0., args=(f,),iprint=0)
def test_fib(fibn):
if fibn<1:
print 'No, it is not'
else:
n=int(round(solve_fib(fibn)))
if int(round(fib(n)))==int(fibn):
print 'Yes, it is. (%d)'%n
else:
print 'No, it is not'
In [67]:
asarray(fib(arange(1,20)), dtype='int64')
Out[67]:
array([ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584, 4181])
In [68]:
test_fib(34)
Yes, it is. (9)
In [69]:
test_fib(4181)
Yes, it is. (19)
In [70]:
test_fib(4444)
No, it is not
Fairly simple and efficient way of doing it
def isInFib(n):
if n == 0: return False
elif n == 1: return True
else:
A = 1
B = 1
FLIP = True
while(True):
new = A + B
if new > n: return False
elif new == n: return True
else:
if(FLIP):
A = new
FLIP = not FLIP
else:
B = new
FLIP = not FLIP
Explanation of Algorithm
I first check if my input is equal to 0 or 1, and return appropriate.
If my input is greater than 1, we go into the else, infinite loop.
A and B represent the last two previous numbers in the sequence. We add A and B to get new, the current Fibonacci number.
We check if new is equal to our input number, if that's true we return true, we are done and complete the function.
If it's greater, that means our number is not in the Fibonacci sequence, since we have surpassed it.
if it's less, we need to keep going! and this is where I think it get's confusing to explain. I want to set up A or B as my current fibonacci sequence number (new), but I have make sure that I keep switching between them, since I don't want one to get left behind. Fibonacci sequence takes the previous 2 numbers and adds them together. I want A and B to be my last two previous sums.
I'll use an example
1,1,2,3,5,8,13
A and B are initially 1. So new is equal to 2 first. I then check if I'm over my input number or equal to it. But if my input number is less. I want to keep going.
I want A to equal new (value = 2) then, before we get to our next iteration of the while loop. So that new will equal 2 + 1 as A + B on the next iteration.
But, then THE next iteration of the loop, I want to set B as 3, and I want to leave A being equal to 2. So I have to keep switching between putting the current fibonacci number I'm at, in A or B. And that's why I have the flip logic! It just keeps switching between True and False.
Try this function:
def isfib(number):
num1 = 1
num2 = 1
while True:
if num2 <= number:
if num2 == number:
return True
else:
tempnum = num2
num2 += num1
num1 = tempnum
else:
return False
Here's how it works:
Set num1 and num2 to 0.
If num2 isn't less than or equal to the number return False.
If num2 is equal to the number return True.
Set add num1 to num2, set num1 to num2's original value and go back to step 2.
num=int(input("Enter a number : "))
n1=0
n2=1
i=1
lst=[]
lst.append(n1)
lst.append(n2)
while i<num-1:
n3=n1+n2
n1=n2
n2=n3
lst.append(n3)
i=i+1
for i in lst:
if (num == i):
print("Fibonacci number")
break
else:
print("Not fibonacci")
def isfib(number):
num1 = 0
num2 = 1
while True:
if num2 <= number:
if num2 == number:
return True
else:
tempnum = num2
num2 += num1
num1 = tempnum
else:
return False
n=int(input())
number=n
fibonacci=isfib(number)
if (fibonacci):
print("true")
elif n==0:
print("true")
else:
print("false")