Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,15 @@
public static long itFibN(int n)
{
if (n < 2)
return n;
long ans = 0;
long n1 = 0;
long n2 = 1;
for(n--; n > 0; n--)
{
ans = n1 + n2;
n1 = n2;
n2 = ans;
}
return ans;
}

View file

@ -0,0 +1,28 @@
/**
* O(log(n))
*/
public static long fib(long n) {
if (n <= 0)
return 0;
long i = (int) (n - 1);
long a = 1, b = 0, c = 0, d = 1, tmp1,tmp2;
while (i > 0) {
if (i % 2 != 0) {
tmp1 = d * b + c * a;
tmp2 = d * (b + a) + c * b;
a = tmp1;
b = tmp2;
}
tmp1 = (long) (Math.pow(c, 2) + Math.pow(d, 2));
tmp2 = d * (2 * c + d);
c = tmp1;
d = tmp2;
i = i / 2;
}
return a + b;
}

View file

@ -0,0 +1,4 @@
public static long recFibN(final int n)
{
return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2);
}

View file

@ -0,0 +1,18 @@
public class Fibonacci {
static final Map<Integer, Long> cache = new HashMap<>();
static {
cache.put(1, 1L);
cache.put(2, 1L);
}
public static long get(int n)
{
return (n < 2) ? n : impl(n);
}
private static long impl(int n)
{
return cache.computeIfAbsent(n, k -> impl(k-1) + impl(k-2));
}
}

View file

@ -0,0 +1,6 @@
public static long anFibN(final long n)
{
double p = (1 + Math.sqrt(5)) / 2;
double q = 1 / p;
return (long) ((Math.pow(p, n) + Math.pow(q, n)) / Math.sqrt(5));
}

View file

@ -0,0 +1,9 @@
public static long fibTailRec(final int n)
{
return fibInner(0, 1, n);
}
private static long fibInner(final long a, final long b, final int n)
{
return n < 1 ? a : n == 1 ? b : fibInner(b, a + b, n - 1);
}

View file

@ -0,0 +1,18 @@
import java.util.function.LongUnaryOperator;
import java.util.stream.LongStream;
public class FibUtil {
public static LongStream fibStream() {
return LongStream.iterate( 1l, new LongUnaryOperator() {
private long lastFib = 0;
@Override public long applyAsLong( long operand ) {
long ret = operand + lastFib;
lastFib = operand;
return ret;
}
});
}
public static long fib(long n) {
return fibStream().limit( n ).reduce((prev, last) -> last).getAsLong();
}
}