Skip to content

Instantly share code, notes, and snippets.

@gixxerblade
Created June 20, 2022 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gixxerblade/0e485b4be1c6e962bfc61030a3b2d95f to your computer and use it in GitHub Desktop.
Save gixxerblade/0e485b4be1c6e962bfc61030a3b2d95f to your computer and use it in GitHub Desktop.
// https://replit.com/@gixxerblade/previous-fibonacci-number#index.ts
/**
* Given a Fibonacci number, give the previous Fibonacci number.
* If the number given is not a Fibonacci number, return -1.
*/
const isPerfectSquare = (num: number): boolean => {
// Perfect square: Floor square root then square number. Are they equal?
const factor = Math.floor(Math.sqrt(num))
return factor * factor === num
}
const isFibonacciNumber = (num: number): boolean => {
// N is a Fibonacci number if and only if ( 5*N2 + 4 ) or ( 5*N2 – 4 ) and is a perfect square
return isPerfectSquare(5 * Math.pow(num, 2) + 4) || isPerfectSquare(5 * Math.pow(num, 2) - 4)
}
const previousFibonacci = (num: number): number => {
if (isFibonacciNumber(num)) {
// Previous === N / ((1 + sqrt(5)) / 2.0) floored
return Math.round(num / ((1 + Math.sqrt(5)) / 2))
}
// Not a Fibbonacci number
return -1
}
const fibbonacci = (num: number): number => {
if (num == 0) return 0;
if (num == 1) return 1;
else {
return fibbonacci(num - 1) + fibbonacci(num - 2);
}
};
type Fib = {
fibbonacci: number,
previousFibbonacci: number,
}
const driver = (num = 0): Fib => {
const fib = fibbonacci(num)
return {
fibbonacci: fib,
previousFibbonacci: previousFibonacci(fib)
}
}
interface Result extends Fib {
step: number
}
// Calculates fibbonacci and previousFibbonacci up to supplied number
const main = (num: number): Result[] => {
let res: Result[] = [];
for (let i = 0; i < num; i++) {
res.push({...driver(i), step: i});
}
return res
}
console.log(main(20))
// test non fibonacci
console.log(previousFibonacci(9)) // -1
console.log(previousFibonacci(6)) // -1
console.log(previousFibonacci(7)) // -1
console.log(previousFibonacci(2585)) // -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment