-
Notifications
You must be signed in to change notification settings - Fork 113
Expand file tree
/
Copy pathLucas.java
More file actions
61 lines (56 loc) · 1.76 KB
/
Copy pathLucas.java
File metadata and controls
61 lines (56 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.util.InputMismatchException;
import java.util.Scanner;
public class Lucas {
// This class returns the nth element of the Lucas numbers where n is a positive integer (or zero) input by the user
public static void main(String[] args) {
System.out.println("The Nth element of the Lucas numbers is " + lucas());
}
public static int userInput() {
Scanner scanner = new Scanner(System.in);
int n = -1;
// The loop is used to check if the number input by the user is a positive integer or zero
while(true) {
// Keeps track if exception was encountered
boolean exception = false;
try {
System.out.print("Enter a number: ");
// Prompt the user to enter a number
n = scanner.nextInt();
}
// Catches an exception if the user input is not an integer
catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter an integer input.\n");
// Discards the invalid token inputed to avoid an infinite loop
scanner.next();
// True if exception was encountered
exception = true;
}
if(n > -1) {
scanner.close();
return n;
}
// Else a negative integer was inputed
else if(exception == false) {
System.out.println("Invalid number. Please enter a positive number.\n");
}
}
}
public static long lucas() {
int n = userInput();
switch(n) {
case 0: {
return 2;
}
case 1: {
return 1;
}
case 2: {
return 3;
}
// Defaults if n is greater than 2, and we use Ln = phi^n - (phi)^-n where phi is the golden ratio
default: {
return Math.round(Math.pow((1+Math.sqrt(5))/2,n) - Math.pow((-1+Math.sqrt(5))/2,n));
}
}
}
}