Next prime number algorithm - algorithm

i want to know if there is a easy way to find the prime number next to X.
For example, if X=2, the next prime will be 3. The algorithm that i have would be ok, if i wanted to know little numbers but i want to calculate like X=3 million.
I found a algorithm to calculate primes, but it takes a lot of time to calculate them, since it calculates all primes from 0 to X... For example for 1 million, it takes almost 2 minutes.
Question is... How can i find the next prime number? Is there an efficient algorithm? Best solution i found is to check if X+1 is prime and increase until one is found...

What you need is to test for primality each number beginning at X. You can find such tests implemented in the GMP library or you can look at the snippet for Miller-Rabin algorithm in Rosetta code.

One possible solution is instead of increasing the number by one, you can increment the number by two if the number is odd else increment by one and then in all future iterations increment by two.
Like in the below code snippet
if (num is odd)
check_prime_of(num+2);
else /*num is even and not equal to 2*/
check_prime_of(num+1);

I can double the speed of "if x+1 is prime" ..... For all x > 2, then x+1 will never be prime, so test x+2 instead :)
Other than that, no. There is no efficient algorithm to find the next prime after X. The "long time to calculate" is what makes public key cryptography (the basis of much of security on the Internet) possible. Public key is based on the difficulty of finding the two prime factors of a given large number; if finding the next prime after X was easy, then you could simply start at the square root of the large number and start counting up.

Related

Find minimum steps to convert all elements to zero

You are given an array of positive integers of size N. You can choose any positive number x such that x<=max(Array) and subtract it from all elements of the array greater than and equal to x.
This operation has a cost A[i]-x for A[i]>=x. The total cost for a particular step is the
sum(A[i]-x). A step is only valid if the sum(A[i]-x) is less than or equal to a given number K.
For all the valid steps find the minimum number of steps to make all elements of the array zero.
0<=i<10^5
0<=x<=10^5
0<k<10^5
Can anybody help me with any approach? DP will not work due to high constraints.
Just some general exploratory thoughts.
First, there should be a constraint on N. If N is 3, this is much easier than if it is 100. The naive brute force approach is going to be O(k^N)
Next, you are right that DP will not work with these constraints.
For a greedy approach, I would want to minimize the number of distinct non-zero values, and not maximize how much I took. Our worst case approach is take out the largest each time, for N steps. If you can get 2 pairs of entries to both match, then that shortened our approach.
The obvious thing to try if you can is an A* search. However that requires a LOWER bound (not upper). The best naive lower bound that I can see is ceil(log_2(count_distinct_values)). Unless you're incredibly lucky and the problem can be solved that quickly, this is unlikely to narrow your search enough to be helpful.
I'm curious what trick makes this problem actually doable.
I do have an idea. But it is going to take some thought to make it work. Naively we want to take each choice for x and explore the paths that way. And this is a problem because there are 10^5 choices for x. After 2 choices we have a problem, and after 3 we are definitely not going to be able to do it.
BUT instead consider the possible orders of the array elements (with ties both possible and encouraged) and the resulting inequalities on the range of choices that could have been made. And now instead of having to store a 10^5 choices of x we only need store the distinct orderings we get, and what inequalities there are on the range of choices that get us there. As long as N < 10, the number of weak orderings is something that we can deal with if we're clever.
It would take a bunch of work to flesh out this idea though.
I may be totally wrong, and if so, please tell me and I'm going to delete my thoughts: maybe there is an opportunity if we translate the problem into another form?
You are given an array A of positive integers of size N.
Calculate the histogram H of this array.
The highest populated slot of this histogram has index m ( == max(A)).
Find the shortest sequence of selections of x for:
Select an index x <= m which satisfies sum(H[i]*(i-x)) <= K for i = x+1 .. m (search for suitable x starts from m down)
Add H[x .. m] to H[0 .. m-x]
Set the new m as the highest populated index in H[0 .. x-1] (we ignore everything from H[x] up)
Repeat until m == 0
If there is only a "good" but not optimal solution sought for, I could imagine that some kind of spectral analysis of H could hint towards favorable x selections so that maxima in the histogram pile upon other maxima in the reduction step.

How to use the Pisano Period to find the Last Digit of the Sum of Fibonacci Numbers?

I'm taking an online algorithms course, and I've come across a problem where I need to find the last digit of the sum of the Fibonacci numbers up the nth (current) number.
I need some help connecting the dots. As I understand it, the "Last Digit of the Sum of Fibonacci Numbers" problem has a solution that is somehow related to the Pisano Period.
But I don't really understand what that means.
The Pisano Period was used to calculate the remainder given some value of m for an extremely large Fibonacci Number, which was the focus of a prior problem (I.E., Solve Fn mod m = ???).
Forum posts (and the instruction set) seem to suggest that the length can somehow help us quickly zero in on the sum for the current Fibonacci without having to actually build up to it normally through a loop.
I would rather avoid just looking at someone else's solution if possible, so if anyone has any useful hints that can help me see the missing link, I would really appreciate it.
The last digit of a Fibonacci number is just that number reduced modulo 10. Pisaso periods are the periods of which the sequence of fibonacci numbers, modulo some base, repeat. So, if you're interested in F(x) mod 10, you'd interested in the Pisaso Period p(10).
If we have this period, say it was something like [1, 5, 2, 7, 0] (its not, but for sake of example), we'd know that the 3rd integer in the sequence ended with a "2". And because it repeats, we'd know the 8th integer also ends in a "2", and the 13th...
Generalizing this, we could say that the last digit of the number N could be found at the ith index in our list we just built, for i satisfying N = 5 * k + i, where k is just any integer, and 5 comes from the fact that our list has 5 elements (and thus repeats every 5 values). Rewriting this, we could say i = N mod 5.
Putting that all together (spoilers), we just need to find the actual values of the repeating sequence mod 10, and then take our input value N (for finding the Nth Fibonacci number mod 10), and index into said repeatingSequence at index N mod len(repeatingSequence) for our answer.
For reference, for base 10, the actual repeating sequence is:
011235831459437077415617853819099875279651673033695493257291

Algorithm to list all possible ways to break a number into k factors?

As part of my effort to explore algorithms through project Euler, I'm trying to write a method that will accept an integer 'n', number of factors 'k' and factorize it. If its not possible, it will throw an error.
For instance, if I enter factorize(13257440,3), the function will return a list of all possible unique sets with 3 elements where the product of the 3 elements is equal to 13257440.
My first though is to generate a multi-set of prime factors of n (with 'm' representing the size of the set), then partition the set into k partitions. Once partition sizes are determined, I would treat it as a combinations problem.
I'm having trouble however formulating algorithms for the two parts above, and have no idea where to start. Am I over complicating a simple problem with a simple solution? If not, what are some recommended approaches? Thanks!
primes decomposition
find all primes that can divide n without remainder. Use sieve of Eratosthenes to speed up the process considerably.
You can use/modify mine (warning this link is project Euler spoiler)
get primes up to n in C++
now you need to modify the code so the prime list will change to multiplicants list. For example if n=12 this will found { 2,3 } and you need { 2,2,3 } so if divider prime found check it again and again until it is not divisible anymore each time lessen the n.
Add a flag to each found prime (is used?) to speed up the next step...
The combination part
I assume the multiplicants can be the same so add k times 1 to the primes list at start and create function that create all possibilities of numbers up to some x from found unused primes. Add the counter for unused primes m so at start the m is set to prime list size and the flags are all set to unused.
Now you need to find all possibilities of using 1..m-k+1 numbers from the list. Each iteration set the picked number as used and decrease m so it is something like:
for (o=1;o<=m-k+1;o++)
here find all combination of o unused numbers so handle it as o digit number generation with base o without digit repetitions it is o! permutations.
You can use this (warning this link is Euler spoiler):
permutations in C++
do not forget to set flag for each used number and unset it after iteration is done. Rewrite this function so it is iterative with calls findfirst(), findnext() similar to mine permutation class.
Now you can nest all this k times (with use of nested fors from the permutation link or via recursion each time lessen the k and n)

Generate a random number using coin flips while guarenteeing termination

The usual method to generate a uniform random number 0..n using coin flips is to build a rng for the smallest power of two greater than n in the obvious way, then whenever this algorithm generates a number larger than n-1, throw that number away and try again.
Unfortunately this has worst case runtime of infinity.
Is there any way to solve this problem while guaranteeing termination?
Quote from this answer https://stackoverflow.com/a/137809/261217:
There is no (exactly correct) solution which will run in a constant
amount of time, since 1/7 is an infinite decimal in base 5.
Now ask Adam Rosenfield why it is true :)

Finding numbers whose digits sum to a prime

I was trying to solve this problem on SPOJ, in which I have to find how many numbers are there in a range whose digits sum up to a prime. This range can be very big, (upper bound of 10^8 is given). The naive solution timed out, I just looped over the entire range and checked the required condition. I cant seem find a pattern or a formula too. Could someone please give a direction to proceed in??
Thanks in advance...
Here are some tips:
try to write a function that finds how many numbers in a given range have a given sum of the digits. Easiest way to implement this is to write a function that returns the number of numbers with a given sum of digits up to a given value a(call this f(sum,a)) and then the number of such numbers in the range a to b will be f(sum,b) - f(sum, a - 1)
Pay attention that the sum of the digits itself will not be too high - up to 8 * 9 < 100 so the number of prime sums to check is really small
Hope this helps.
I (seriously) doubt whether this 'opposite' approach will be any faster than #izomorphius's suggestion, but it might prompt some thoughts about improving the performance of your program:
1) Get the list of primes in the range 2..71 (you can omit 1 and 72 from any consideration since neither is prime).
2) Enumerate the integer partitions of each of the prime numbers in the list. Here's some Python code. You'd want to modify this so as not to generate partitions which were invalid, such as those containing numbers larger than 9.
3) For each of those partitions, pad out with 0s to make a set of 8 digits, then enumerate all the permutations of the padded set.
Now you have the list of numbers you require.
Generate the primes using the sieve of Eratosthenes up to the maximum sum (9 + 9...). Put them in a Hash table. Then you could likely loop quickly through 10^8 numbers and add up their sums. There might be more efficient methods, but this should be quick enough.

Resources