/** * Matt Kretchmar * February 20, 2006 * Period.java * This program searches a sequence of numbers looking for the largest * possible period of repeated numbers. */ import java.util.Scanner; class Period { public static void main ( String [] args ) { Scanner keyboard = new Scanner(System.in); // Read how many numbers in array int n = keyboard.nextInt(); // Read in n numbers to store in our array int data[] = new int[n]; for ( int i = 0; i < n; i++ ) { data[i] = keyboard.nextInt(); } // We look for possibly periods starting with the smallest possible period length. // For each period length, compare numbers that are "period" spaces apart in the // sequence. If we find any that aren't matches, then this sequence is not periodic // with lenght=period. If all such pairs match, then we have found period, quit and report. boolean foundPeriod = false; int period = 0; // potential periods while ( !foundPeriod && period < n-1 ) { // Test next period length period++; // Assume this sequence is periodic with length=period foundPeriod = true; int j = 0; // scan through the sequence comparing each pair of numbers that are // period spaces apart. while ( j+period < n && foundPeriod ) { if ( data[j] != data[j+period] ) // if we find a pair that don't match, then no longer possible match foundPeriod = false; j++; } } if ( foundPeriod ) System.out.println("The sequence is periodic with period " + period + "."); else System.out.println("The sequence is not periodic."); } }