A Mersenne number is any number that can be written as 2^p−1 for some p . For example, 3 is a Mersenne number ( 2^2-1 ) as is 31 ( 2^5-1 ). We will see later on that it is easy to test if Mersenne numbers are prime.
Write a function that accepts an exponent pp and returns the corresponding Mersenne number.
Ans- def mersenne_number(p):
m_number =(2**p)-1
Mersenne numbers can only be prime if their exponent, pp , is prime. Make a list of the Mersenne numbers for all primes pp between 3 and 65 (there should be 17 of them).
def is_prime(number):
if number <= 1:
return False
for factor in range(2, number):
if number % factor == 0:
return False
return True
def get_primes(n_start, n_end):
for number in range(n_start, n_end):
if is_prime(number):
mersenne_number(number)
mersennes =get_primes(3,65)
The next cell shows a dummy solution, a list of 17 sevens. Alter the next cell to make use of the functions you've defined above to create the appropriate list of Mersenne numbers.
SO HOW TO MAKE THE LIST OF MERSENNE NUMBERS???
A Mersenne number is any number that can be written as 2^p−1 for some p.
def mersenne_number(p):
return ((2**p)-1)
def mersenne_number(p):
return ((2**p)-1)
def is_prime(number):
if number <= 1:
return False
for factor in range(2, number):
if number % factor == 0:
return False
return True
list_ = []
def get_primes(n_start, n_end):
for number in range(n_start, n_end):
if is_prime(number):
list_.append(mersenne_number(number))
return list_
mersennes =get_primes(3,65)
Related
Wrote this code in comp sci class and I cant get it to work, it always returns as false every time I run it. Its supposed to be a recursive binary search method... Any idea why it only returns false?
arr = [1,10,12,15,16,122,132,143,155]
def binarysearch(arr,num):
arr2 = []
if (len(arr) == 1):
if (arr[0] == num):
return 1
else:
return 0
for i in range (len(arr)/2):
arr2.append(0)
if (arr[len(arr)/2]>num):
for x in range (len(arr)/2,len(arr)):
arr2[x-(len(arr)/2)]=arr[x]
return binarysearch(arr2,num)
if(arr[len(arr)/2]<num):
for x in range(0, len(arr) / 2 ):
arr2[x] = arr[x]
return binarysearch(arr2, num)
num = raw_input("put number to check here please: ")
if(binarysearch(arr,num)==1):
print "true"
else:
print "false"
You're doing vastly more work than you need to on things that Python can handle for you, and the complexity is masking your problems.
After your base case, you have two if statements, that don't cover the full range—you've overlooked the possibility of equality. Use if/else and adjust the ranges being copied accordingly.
Don't create a new array and copy stuff, use Python's subranges.
Don't keep repeating the same division operation throughout your program, do it once and store the result.
If you want to print True/False, why not just return that rather than encoding the outcome as 0/1 and then decoding it to do the print?
Recall that raw_input returns a string, you'll need to convert it to int.
The end result of all those revisions would be:
def binary_search(arr,num):
if (len(arr) == 1):
return (arr[0] == num)
mid = len(arr) / 2
if (arr[mid] > num):
return binary_search(arr[:mid], num)
else:
return binary_search(arr[mid:], num)
num = int(raw_input("put number to check here please: "))
print binary_search(arr,num)
Write a function iterate with the following arguments:
f: a function
start: a numeric starting value
tol: a numerical tolerance (default value 1e-6)
itmax: a maximum number of iterations (default value 1000)
Starting from the initial value, your function should keep repeating calls to the function (e.g. y=f(y)) until the absolute value of f(y)-y is less than tol or the number of iterations is equal to itmax. For example, if start=1.01, f is math.sqrt, and tol=1e-4, the sequence would look like this:
On step 6, the absolute value of the difference is less than the tolerance (1e-4), so the function returns [6, 1.0000777399813863].
Tests (should all be True):
def approx_equal(x,y,tol=1e-8):
"""helper function: test whether all elements of
x and y are equal within tolerance
"""
if len(x) != len(y):
return(False)
for i in range(len(x)):
if (abs(x[i]-y[i])>tol):
return(False)
return(True)
def disc_logist(x):
"""discrete logistic function"""
return(1.5*x*(1-x))
print(approx_equal(iterate(disc_logist,0.5),[15, 0.33333433255312184]))
print(approx_equal(iterate(disc_logist,0.5,tol=1e-8),[22, 0.33333334113969143]))
def half(x):
"""just what it says"""
return(x/2)
print(approx_equal(iterate(half,1000),[29, 9.313225746154785e-07]))
import math
print(approx_equal(iterate(math.sqrt,1.01,tol=1e-4),[6, 1.0000777399813863]))
print(approx_equal(iterate(math.cos,0),[34, 0.7390855263619245]))
print(approx_equal(iterate(math.cos,0,tol=1e-8),[46, 0.7390851366465718]))
print(approx_equal(iterate(math.cos,0,itmax=5),[5, 0.7013687736227565]))
This is what i have so far:
def iterate(f,start,tol=1e-6,itmax=1000):
"""function should keep repeating calls to the function until the absolute
value of f(y)-y is less than tol or number of iterations is equal to itmax
:f: a function
:start: a numeric starting value
:tol: a numerical tolerance
:itmax: a maximum number of iterations"""
import math
y=start
for i in range(itmax):
y_2=f(y)
if abs(y_2 - y) <tol:
return y
else:
y=y_2
The answer for your immediate problem is to return not a single number, but a two element list containing first the number of iterations and second the answer - note that the instructions say (my emphasis):
On step 6, the absolute value of the difference is less than the tolerance (1e-4), so the function returns [6, 1.0000777399813863].
def iterate(f,start,tol=1e-6,itmax=1000):
"""function should keep repeating calls to the function until the absolute
value of f(y)-y is less than tol or number of iterations is equal to itmax
:f: a function
:start: a numeric starting value
:tol: a numerical tolerance
:itmax: a maximum number of iterations"""
import math
y=start
for i in range(itmax):
y_2=f(y)
if abs(y_2 - y) <tol:
# Return the successful value - the last result, not the last input
return [i, y_2]
else:
y=y_2
# Return the next answer
return [itmax, f(y)]
This will get approx_equal() working, but I haven't tested it completely to see if all the results match up.
How can I interact with the values of a generator expression? For instance:
def sumValues(*args):
# compute the sum of values
sumValues(abs(x) for x in range(0,10))
When the range is known (e.g., we know the range is [0,10)), we can put a for loop, but what if the range is unknown?
it depend on how you want your function to be called, if you want to call it with list, generator, or more generally a iterable (anything that can be used in a for-loop) and imitate the behavior of the build-in sum then
def my_sum(iterable):
total = 0
for x in iterable:
total += x
return total
and use like
my_sum(range(10))
my_sum(abs(x) for x in range(0,10))
my_sum([1,2,3,4,5,6])
if you want to imitate the behavior of max and use it as above and also like my_sum(1,2), my_sum(1,2,3), my_sum(1,2,3,4,5,6,7), etc. then
def my_sum(*argv):
total = 0
values = None
if len(argv) == 1:
values = argv[0]
else:
values = argv
for x in values:
total += x
return total
I figured. Here's the answer:
def sumValues(*args):
# compute the sum of values
total = 0
for item in args[0]:
total += item
return total
print(sumValues(abs(x) for x in range(0,10)))
[output] => 45
I want to write a program sort like solving Diophantine Equation:
That is able to identify any number from 0 to 100 that is exactly with combination of 6a+9b+20C, when a, b, c are all non-negative integer between 0 to 10.
And also I want to write a program that is able to identify any number from 0 to 100 that is not exactly with combination of 6a+9b+20C.
I try with following with problem 2:
for num in range(0, 100):
prime = True
for i in range(3, 20, 3):
if (num%i==0):
prime=False
if prime:
print 'Largest number that cannot be bought in exact quantity', num
I can only get as far as this.
This function will give you a dictionary output which will contain all the numbers that are not the combination and the number which is the combination of your equation :-
def inputNo( a, b, c ):
result = {"isComb":[], "notComb":[]}
for i in range(1,100):
if ((6*a)+(9*b)+(20*c) == i ):
result['isComb'].append(i)
else:
result['notComb'].append(i)
return result
Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
Note: is_prime takes an integer as a parameter and returns True if and only if that integer is prime.
Well, I wrote is_prime function like this:
def is_prime(n):
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
but it works except for n==0. How can I fix it to make it work for every integer?
I'm trying to find out answers for both how to write function to get the sum of first n prime numbers and how to modify my is_prime function, which should work for all possible input, not only positive numbers.
Your assignment is as follows.
Assume the availability of a function is_prime. Assume a variable n has been associated with a positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.
As NVRAM rightly points out in the comments (and nobody else appears to have picked up on), the question states "assume the availability of a function is_prime".
You don't have to write that function. What you do have to do is "write the statements needed to compute the sum of the first n prime numbers".
The pseudocode for that would be something like:
primes_left = n
curr_num = 2
curr_sum = 0
while primes_left > 0:
if is_prime(curr_num):
curr_sum = curr_sum + curr_num
primes_left = primes_left - 1
curr_num = curr_num + 1
print "Sum of first " + n + " primes is " + curr_sum
I think you'll find that, if you just implement that pseudocode in your language of choice, that'll be all you have to do.
If you are looking for an implementation of is_prime to test your assignment with, it doesn't really matter how efficient it is, since you'll only be testing a few small values anyway. You also don't have to worry about numbers less than two, given the constraints of the code that will be using it. Something like this is perfectly acceptable:
def is_prime(num):
if num < 2:
return false
if num == 2:
return true
divisor = 2
while divisor * divisor <= num:
if num % divisor == 0:
return false
divisor = divisor + 1
return true
In your problem statement it says that n is a positive integer. So assert(n>0) and ensure that your program outer-loop will never is_prime() with a negative value nor zero.
Your algorithm - trial division of every successive odd number (the 'odd' would be a major speed-up for you) - works, but is going to be very slow. Look at the prime sieve for inspiration.
Well, what happens when n is 0 or 1?
You have
i = 2
while i < n: #is 2 less than 0 (or 1?)
...
return True
If you want n of 0 or 1 to return False, then doesn't this suggest that you need to modify your conditional (or function itself) to account for these cases?
Why not just hardcode an answer for i = 0 or 1?
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i < n:
if n % i == 0:
return False
i += 1
return True
And you could further improve the speed of your algorithm by omitting some numbers. This script only checks up to the square root of n as no composite number has factors greater than its square root if a number has one or more factors, one will be encountered before the square root of that number. When testing large numbers, this makes a pretty big difference.
n = abs(n)
i = 2
if(n == 0 || n == 1)
return true //Or whatever you feel 0 or 1 should return.
while i <= sqrt(n):
if n % i == 0:
return False
i += 1
return True
try this:
if(n==0)
return true
else
n = abs(n)
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True