My first learned programming language is C language.
My first C language program:
//"@begin_of_source_code"
/* @JUDGE_ID: 7382YR 100 C++ */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
/**** <<<<<<<<<<<<<< The 3n+1 problem >>>>>>>>>>>>>> ****
* Purpose: see follows sub-function description *
********************************************************/
unsigned long _max(unsigned long p, unsigned long q);
unsigned long lenght(unsigned long n, unsigned long cycle_lenght);
void swap(unsigned long *a, unsigned long *b);
int main(void)
{
unsigned long i, j; // input - the maximum cycle lenght of i to j
#ifndef ONLINE_JUDGE
close (0); open ("myprog.in", O_RDONLY);
close (1); open ("myprog.out", O_WRONLY | O_CREAT, 0600);
#endif
scanf("%d%d", &i, &j);
if (i > j) { swap(i, j); } // check if i <= j
printf("%d %d %d\n", i, j, _max(i, j));
return (0);
}
/*******************************************************
* _max -- to get maximum cycle lenght between p and q *
* p -- lower bound *
* q -- upper bound *
* *
* Return *
* max -- asked *
*******************************************************/
unsigned long _max(unsigned long p, unsigned long q)
{
unsigned long max = 1; // maximum cycle lenght. start with 1.
for (unsigned long ctr = p; ctr < q+1; ctr++) // ctr - counter.
{
if(lenght(ctr,0) > max)
{
max = lenght(ctr,0);
}
}
return max;
}
/*******************************************************
* lenght -- to get the cycle lenght of a number n *
* *
* n -- that number *
* temp -- to store current lenght (for recusion) *
* *
* Return *
* temp. if n == 1, or continue *
*******************************************************/
unsigned long lenght(unsigned long n, unsigned long temp)
{
temp++;
if (n == 1)
return temp;
else
{
if (n % 2 == 0)
n = n / 2;
else
n = 3 * n + 1;
return lenght(n, temp);
}
}
void swap(unsigned long *a, unsigned long *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
//"@end_of_source_code"
Really ugly.
沒有留言:
張貼留言