To show how to check primality with the Lucas sequence, let’s look at
an example. Consider the first few numbers in the Lucas sequence:
1,3,4,7,11,18,29,47,76,123,...
If we are interested to see if a particular number, say 7, is prime,
we take the 7th number in the Lucas sequence and subtract 1. The 7th
Lucas number is 29. Subtract 1 and we have 28. Now, if this result is
evenly divisible by 7, 7 is probably prime. In our example, 28 is
divisible by 7, so it is probably prime. We call these numbers Lucas
pseudoprimes.
If we were interested in another number, say 8, we would take the 8th
Lucas number and subtract 1. In this case, we get 46, which is not
evenly divisible by 8. So, 8 is definitely not prime. This method is
useful for filtering out composite numbers.
So, the general procedure to determine if an integer p could possibly
be prime is as follows:
Find the pth Lucas number
Subtract 1
Check to see if p divides the result evenly
Define a SCHEME function, named (lucas-pseudoprime p) which uses
this approach to determine if an integer p is a Lucas pseudoprime.
I have this so far:
(define (lucas-pseudoprime p)
(define (helper-lucas goal current next)
(if (= goal current)
(head next)
(helper-lucas goal (+ current 1) next))
(let ((solution (- p 1))
(if (= (module solution p) 0) #t
#f)))))
Not sure what's going wrong with this.
Related
How do you create a function that will allow you to find the Nth digit from the right in a large number? For example, (f 2345 2) will yield 4. I am a beginning student so I am programming with DrRacket and I'm hoping that the code can be usable in Racket.
Remember that the right most digit is the least significant and thus you can cut it off by taking the quotient by 10 and get the last by taking the remainder by 10.
For nth index you first need to get the remainder of a division by (expt 10 n) and the quotient of that and (expt 10 (- n 1)).
Imagine your function taking a base such that you can pick the 3rd octal digit like this:
(f #o143 #o3 #o10) ; ==> 1
; same in decimal notation
(f 99 3 8) ; ==> 1
If
Mp=2p-1 is prime ⇒
⇒ 2p-2⋮6 or 2p⋮6 ⇒
⇒ 2p-1-1⋮3 or 2p-1⋮3 ⇒
⇒ 2n-1⋮3 or 2n⋮3, n=p-1
In order to pick huge values for p to test if Mp is a prime number, I believe this is a good preliminary test before going with the computationally expensive Lucas-Lehmer test.
But what is the fastest, most efficient way to test if two numbers, 2n-1 and 2n, are divisible by 3?
Other info that we can use from this is that n always ends in 0, 2, 6 or 8 (because p=n+1 is a prime). Maybe it helps in some way.
It's easy to prove:
2^n mod 3
== 1 if n is even
== 2 if n is odd
using mathematical induction.
So 2n is never divisible by 3, and 2n-1 is divisible by 3 if and only if n is even.
Sum the digits, if result is dividable by 3 then it is.
ea
25681 = 2+5+6+8+3 = 24 (=2+4) = 6 is dividable.
if u're dealing with bigints and the inputs are already in an ASCII string format of some sort, you can simply :
high-speed scrub away all instances of 0, 3, 6, and 9 via regex ::gsub() (or equiv.),
measure the string length() / len() at that point,
count # of instances of 2, 5, and 8
sum up the values of the 2 sub-bullet points, then mod % 3
This works no matter how large the big-int is.
But yes, like others have mentioned already, no point to run it through this algorithm if you already knew that the input is an integer power of an integer base, and if the base itself isn't divisible by 3, then neither would any of its integer powers.
I've written a function, sieve(n), that uses the Sieve of Eratosthenes to return an array of all primes up to n.
sieve(25) # ==> [2, 3, 5, 7, 11, 13, 17, 19, 23]
The source for this function can be read here.
I want to refactor this now so that sieve(n) will return the nth prime. I'm just not sure about how I'd do that. I don't want to write an entirely new more elaborate function, so it seems like the best method is to figure out what value the sieve should count up to.
For example, if I ask for the 27th prime, the sieve's initial list of integers should be 2 up to (something I know the 27th prime isn't greater than). But is there a simple way to work out what that value is?
I researched this question and found this Quora post which said that the nth prime must be between n*Math.log(n) + n*(Math.log(Math.log(n))-1) and n*Math.log(n) + n*Math.log(Math.log(n)) (where Math.log is Ruby for the natural logarithm), but simply making list an array of numbers between those two figures makes the sieve yield weird values, like 56 for the 15th prime (56 is not prime and the answer should be 47).
As you can guess, I'm totally out of my element here. If someone could offer me some advice I'd really appreciate it.
The sieve of Eratosthenes always has to start from the beginning; you can't sieve in some arbitrary interval since you'd loose all smaller primes. So you don't have to care for a lower bound, only for an upper bound. Which you gave, and which Wikipedia confirms:
pn < n ln (n ln n) for n ≥ 6
So simply take that bound, plug in your n and iterate till you have found n primes. Your sieve will usually be a bit too big, but not too much if the bound is reasonably tight, which I expect to be the case.
See here for a table of that bound or here for a plot. By the way, the code creating the table is doing the same thing. I wanted at least 500 entries, so I computed
n = 500
lst = list(range(2, ceil(n*log(n*log(n)))))
ps = []
while lst:
p = lst[0] # next prime
ps.append(p)
lst = [i for i in lst if i % p != 0]
and got a bit over 500 primes out of it, for which I then could show you how the computed bound compares to the actual value.
An iterative version of odd? for non-negative integer arguments can be written using and, or, and not. To do so, you have to take advantage of the fact that and and or are special forms that evaluate their arguments in order from left to right, exiting as soon as the value is determined. Write (boolean-odd? x) without using if or cond, but using and, or, not (boolean) instead. You may use + and -, but do not use quotient, remainder, /, etc.
A number is even if two divides it evenly, and odd if there if there is a remainder of one. In general, when you divide a number k by a number n, the remainder is one element of the set {0,1,…n-1}. You can generalize your question by asking whether, when k is divided by n, the remainder is in some privileged set of remainder values. Since this is almost certainly homework, I do not want to provide a direct answer to your question, but I'll answer this more general version, without sticking to the constraints of using only and and or.
(define (special-remainder? k n special-remainders)
(if (< k n)
(member k special-remainders)
(special-remainder? (- k n) special-remainders)))
This special-remainder? recursively divides k by n until a remainder less than n is found. Then n is tested for its specialness. In the case that you're considering, you'll be able to eliminate special-remainders, because you don't need (member k special-remainders). Since you only have one special remainder, you can just check whether k is that special remainder.
A positive odd number can be defined as 1 + 2n. Thus an odd number is:
If x is 1
If x is greater than 1 and x-2 is odd.
Thus one* solution that is tail recursive/iterative looks like this:
(define (odd? x)
(or (= ...) ; #t if 1
(and ... ; #f if less than 1
(odd? ...))); recurse with 2 less
*having played around with it it's many ways to do do this and still have it iterative and without if/cond.
I'm looking for an algorithm (or better yet, code!) for a the generation of powers, specifically numbers with an odd exponent greater than 1: third powers, fifth powers, seventh powers, and so forth. My desired output is then
8, 27, 32, 125, 128, 216, 243, 343, 512, 1000
and so forth up to a specified limit.
I don't want to store the powers in a list and sort them, because I'm making too many to fit in memory -- hopefully the limit be 1030 or so, corresponding to a memory requirement of ≈ 1 TB.
My basic idea is to have an array holding the current number (starting at 2) for each exponent, starting with 3 and going up to the binary log of the limit. At each step I loop through the exponent array, finding the one which yields the smallest power (finding either pow(base, exponent) or more likely exponent * log(base), probably memoizing these values). At that point call the 'output' function, which will actually do calculations with the number but of course you don't need to worry about that.
Of course because of the range of the numbers involved, bignums must be used -- built into the language, in a library, or self-rolled. Relevant code or code snippets would be appreciated: I feel that this task is similar to some classic problems (e.g., Hamming's problem of generating numbers that are of the form 2x3y5z) and can be solved efficiently. I'm fairly language-agnostic here: all I'll need for my 'output' function are arrays, subtraction, bignum-word comparison, and a bignum integer square root function.
Your example is missing 64=4^3, and 729=9^3.
You want the set of all { n^m } traversed in numerical order, m odd, n integral and n > 1. We know that (for n > 1) that increasing either n or m will increase this value, but short of calculation we can't compare much else.
There are two obvious "dual" ways to do this: keep track of the highest base n you consider, and for all bases less than that, the next exponent m to consider. Then pick the smallest one, and compare it to n^3. Or, the other way around -- keep track of the highest exponent m, and for each exponent smaller than that, keep track of the highest base used, and find the smallest one, and compare it to adding 2^m.
To make keeping track of these numbers efficiently, you'll want to keep them in a priority queue. Now, you still want to minimize the number of entries in the priority queue at a time, so we'll want to figure out which of these two methods does better job of this. It turns out that much higher n values are required to make it to a given point. At number k, the largest value of m seen will be log_2 of k, whereas the largest value of n seen will be k^(1/3).
So, we have a priority queue with elements (v, n, m), where the value v=n^m.
add_priority_queue(2^3, 2, 3)
for m in 5, 7, ....
v = 2^m
while value(peek(queue)) <= v:
(v1, n1, m1) = pop(queue)
if v1 != v print v1
add_priority_queue((n1+1)^m1, n1+1, m1)
add_priority_queue(2^m, 2, m)
Note that we need to check for v1 = v: we can have 2^9 = 512 = 8^3, and only one should be printed out, right?
A Haskell implementation, with a random priority queue grabbed off of hackage.
import Data.MeldableHeap
dropMin q = maybe empty snd (extractMin q)
numbers = generate_values (insert (2^3, 2, 3) empty) 5
generate_values q m = case findMin q of
Nothing -> []
Just (v1, n1, m1) -> case compare v1 (2^m) of
EQ -> generate_values (insert ((n1+1)^m1, n1+1, m1) (dropMin q)) m
LT -> v1 : generate_values (insert ((n1+1)^m1, n1+1, m1) (dropMin q)) m
GT -> 2^m : generate_values (insert (3^m, 3, m) q) (m + 2)
main = sequence_ (map print numbers)
I have a run currently at 177403008736354688547625 (that's 23 digits) and 1.3 GB plaintext output, after 8 minutes
deque numbers // stores a list of tuples - base number, and current odd power value - sorted by the current odd power value
for i = 2 .. infinity
numbers.push_back (i,i^3) // has to be the highest possible number so far
while numbers.peek_front[1] == i // front always has the lowest next value
print i
node = numbers.pop_front
node[1]=node[1]*(node[0]^2)
// put the node back into the numbers deque sorted by the second value in it - will end up being somewhere in the middle
at 2, numbers will be [2,8]
at 3, numbers will be [2,9], [3, 27]
...
at 8, numbers will be [2,8], [3,27].....[8,8^3]
You'll take off the first node, print it out, then put it back in the middle of numbers with the values [2,32]
I think this will work and has a reasonable memory usage.
There's a special case for 1, since 1^N never changes. This will also print out duplicate values for numbers - 256 for instance - and there are fairly simple ways to slightly alter the algorithm to remove those.
This solution is constant time for checking each number, but requires quite a bit of ram.
Consider k lists for numbers 2 .. k+1 numbers. Each list i represents the powers of number i+1. Since each list is a sorted use k-way merging with min heap to achieve what you need.
Min-heap is constructed with first indices of lists as key and after minimum is extracted we remove first element making second element as key and rearrange the heap to get next minimum.
This procedure is repeated till we get all numbers.