How should I start to think to solve this problem? I have solution but I couldn't realize where to start thinking for solution.Write a C program that recognizes a number sequence of given length and prints
the following numbers in the sequence.
The number sequences you should recognize are:
1. Arithmetic Sequences : X_n = X_(n-1) + a , for a>0
2. Geometric Sequences: X_n = X_(n-1) . a, for a>0
3. Fibonnachi Sequences: X_n = X_(n-1) + X_(n-2)
Your input will contain many lines, each line of the linput with the form:
For each such line you will recognize the type of sequence and print as many numbers as required.
Notes:
- The length of sequences and the length of your output can be arbitrary. So please use
loop statements
- If you can not recognize any sequence, print "no sequence" only.
- Each output should be on a different line
Hints:
- 2 numbers do not form a sequence
Btw, here is the solution for ones to have a look:
Code:#include <stdio.h> int main(void) { int given, out; int difference; int ratio; int previous; int preprevious; int current; int currdifference; int currratio; int next; unsigned short arithmetic; unsigned short geometric; unsigned short fibonacchi; int i; /* Loop until the input is finished. First scan the length of the sequence and how many * members we should print */ while ( scanf("%d%d",&given, &out) != EOF ) { /* * We read sequence until it ends */ arithmetic = geometric = fibonacchi = 1; /* Read the sequence */ for (i=0;i<given;i++) { /* For each element of sequence read */ scanf("%d",¤t); if (i > 0) { /* Calculate the differen and ratio */ currdifference = current - previous; currratio = current / previous; } if (i > 1 ) { /* Mark if sequence breaks */ if (currdifference != difference) { arithmetic = 0; } if (currratio != ratio) { geometric = 0; } if (current != previous + preprevious) { fibonacchi = 0; } } preprevious = previous; previous = current; ratio = currratio; difference = currdifference; } /* Print the following elements if more then two numbers are read * and they form a sequence */ if (arithmetic && given > 2) { while (out-- > 0) { next = current + difference; printf("%d ",next); current = next; } } else if (geometric && given > 2) { while (out-- > 0) { next = current * ratio; printf("%d ",next); current = next; } } else if (fibonacchi && given > 2) { previous = preprevious; /* At the end of the loop variables are shifted, we should undo */ while (out-- > 0) { next = current + previous; printf("%d ",next); previous = current; current = next; } } else { printf("no sequence"); } printf("\n"); } }