Sunday, January 18, 2009

UVa problem 10696: sample code, sample algorithm

To solve this problem, one needs to be able to discover the observation that:
if N is greater than 100, the output is N - 10; otherwise it is always 91.

One can discover this observation by running a simple simulation of the recursive F91 function:


001 #include "stdio.h"
002
003 int f91(int n) {
004 if (n <= 100) {
005 return f91(f91(n + 11));
006 }
007 else {
008 return n - 10;
009 }
010 }
011
012 int main() {
013 char line[100];
014
015 int n;
016
017 while (fgets(line, 100, stdin)) {
018 sscanf(line, "%d", &n);
019
020 if (n == 0) {
021 break;
022 }
023
024 printf("%d\n", f91(n));
025 }
026
027 return 0;
028 }


After discovering the pattern, one can then simplify his code like as follows:


001 #include "stdio.h"
002
003 int main() {
004 char line[100];
005 int n
006 , n1;
007
008 while(fgets(line, 100, stdin)) {
009 sscanf(line, "%d", &n);
010
011 if (n == 0) {
012 break;
013 }
014
015 if (n > 100) {
016 n1 = n - 10;
017 }
018 else {
019 n1 = 91;
020 }
021
022 printf("f91(%d) = %d\n", n, n1);
023 }
024
025 return 0;
026 }

No comments:

Post a Comment