Documente Academic
Documente Profesional
Documente Cultură
JAVA :
Use BufferedReader in place of Scanner for input, and PrintWriter for output
result = (result * x) % m;
return result;
}
Optimized method ( O(log n) )
Recursive implementation
long long modExpo (int x, int y, int m) {
if (y == 0)
return 1;
else if (y%2 == 0)
else
}
Iterative implementation
long long modExpo (int x, int y, int m) {
if (y == 0)
return 1;
x = x % m;
long long res = 1;
while (y > 0) {
if (y%2==1)
res = (res * x) % m;
x = (x * x) % m;
y = y/2;
}
return res;
Fibonacci number using fast exponentiation
(Donald E. Knuth)
Sieve of eratosthenes
Features of SOE
● Ancient algorithm for finding all prime numbers up to any
given limit.
● Also used for finding prime numbers in a given range
● Time complexity : O(n log logn)
● Space complexity : O(n)
Algorithm
● Create a list of consecutive integers from 2 through n: (2, 3, 4, ..., n).
● Initially, let p equal 2, the smallest prime number.
● Count to n from 2p in increments of p, and mark them as non-primes in the list
(these will be 2p, 3p, 4p, ...; the p itself should not be marked).
● Find the first number greater than p in the list that is not marked. If there was
no such number, stop. Otherwise, let p now equal this new number (which is
the next prime), and repeat from step 3.
● When the algorithm terminates, the numbers remaining not marked in the list
are all the primes below n.
Segmented sieve
The drawback with sieve of Erastothenes is not the number of
operations it performs but rather its memory requirements.