Determines whether the given string of text represents a Lucas sequence , where
ID: 3725837 • Letter: D
Question
Determines whether the given string of text represents a Lucas sequence, where the given text consists of integer values separated by arbitrary whitespace. A Lucas sequence is any sequence of numbers in which each value (other than the first and second) is the sum of the previous two values. The Fibonacci sequence is one example of a Lucas sequence. Another one would be "-2 1 -1 0 -1 -1 -2 -3 -5 -8". This method returns true if the sequence has fewer than 3 numbers. The behavior is undefined if the provided string contains any non-numeric values.
Parameters:
text - string of text (possibly empty) containing numbers separated by whitespace
Returns:
true if the given sequence of numbers is a Lucas sequence, false otherwise
Explanation / Answer
Java Code:
public class LucasSeq {
public static boolean isLucasSequence(java.lang.String text)
{
String[] seq = text.split(" "); //split into numbers
//if fewer than 3, return true
if(seq.length < 3)
return true;
int a, b, c;
//loop through all numbers and check
for(int i=2; i<seq.length; i++)
{
a = Integer.parseInt(seq[i]);
b = Integer.parseInt(seq[i-1]);
c = Integer.parseInt(seq[i-2]);
//if any number not satisified, return false
if(a != b+c)
return false;
}
return true; //return true
}
public static void main(String[] args) {
System.out.println(isLucasSequence("-2 1 -1 0 -1 -1 -2 -3 -5 -8"));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.