Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <time.h>
- #include <limits.h>
- #define DEBUG 1 // for debuging purpose
- int fibs( int howMany );
- int fibs( int howMany )
- {
- unsigned long int *dataArr;
- int i = 0;
- unsigned long int result = 0;
- if( 3 > howMany )
- {
- if( DEBUG )
- {
- printf("The amount of years is less then 3\n");
- }
- return 0;
- }
- dataArr = ( unsigned long int* )malloc( sizeof( unsigned long int ) * ( howMany + 1 ) );
- if( NULL == dataArr )
- {
- if( DEBUG )
- {
- printf("Memory for storing fibs data wasn't allocated\n");
- }
- return 0;
- }
- dataArr[1] = dataArr[2] = 1;
- if( DEBUG )
- {
- printf("Amount of rabbits in 1 year is: %lu\n", dataArr[ 1 ] );
- printf("Amount of rabbits in 2 year is: %lu\n", dataArr[ 2 ] );
- }
- for( i = 3; i <= howMany; i++ )
- {
- dataArr[ i ] = dataArr[ i - 1 ] + dataArr[ i - 2 ];
- if( DEBUG )
- {
- printf("Amount of rabbits in %d year is: %lu\n", i, dataArr[ i ] );
- }
- }
- result = dataArr[ howMany ];
- free( dataArr );
- return result;
- }
- // Second parameter might be the amount of years
- int main( int argc, char **argv )
- {
- // Timing
- time_t start, end;
- clock_t start1, end1;
- double dif;
- double dif1;
- //unsigned long int years = ULONG_MAX; // by default it should be minimum, so 3
- int years = 3;
- unsigned long int howManyResult = 0;
- if( ! DEBUG )
- {
- printf("It's: %d\n", years);
- return 0;
- }
- if( argc >= 2 )
- {
- years = atoi( argv[1] );
- }
- time( &start );
- start1 = clock();
- //printf("We started at %ld\n", start);
- howManyResult = fibs( years );
- time( &end );
- end1 = clock();
- //printf("We ended at %ld\n", end);
- if( 0 != howManyResult )
- {
- printf("For %d years the amount of rabbits is: %lu\n", years, howManyResult);
- }
- dif = difftime( end, start );
- dif1 = ((double)(end1 - start1)) / CLK_TCK;
- printf("It took program %.2lf seconds\n", dif);
- printf("It took program %3.3lf seconds\n", dif1);
- return 0;
- }
Add Comment
Please, Sign In to add comment