A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
41
Task/Hailstone-sequence/C/hailstone-sequence-1.c
Normal file
41
Task/Hailstone-sequence/C/hailstone-sequence-1.c
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int hailstone(int n, int *arry)
|
||||
{
|
||||
int hs = 1;
|
||||
|
||||
while (n!=1) {
|
||||
hs++;
|
||||
if (arry) *arry++ = n;
|
||||
n = (n&1) ? (3*n+1) : (n/2);
|
||||
}
|
||||
if (arry) *arry++ = n;
|
||||
return hs;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int j, hmax = 0;
|
||||
int jatmax, n;
|
||||
int *arry;
|
||||
|
||||
for (j=1; j<100000; j++) {
|
||||
n = hailstone(j, NULL);
|
||||
if (hmax < n) {
|
||||
hmax = n;
|
||||
jatmax = j;
|
||||
}
|
||||
}
|
||||
n = hailstone(27, NULL);
|
||||
arry = malloc(n*sizeof(int));
|
||||
n = hailstone(27, arry);
|
||||
|
||||
printf("[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\n",
|
||||
arry[0],arry[1],arry[2],arry[3],
|
||||
arry[n-4], arry[n-3], arry[n-2], arry[n-1], n);
|
||||
printf("Max %d at j= %d\n", hmax, jatmax);
|
||||
free(arry);
|
||||
|
||||
return 0;
|
||||
}
|
||||
31
Task/Hailstone-sequence/C/hailstone-sequence-2.c
Normal file
31
Task/Hailstone-sequence/C/hailstone-sequence-2.c
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
#include <stdio.h>
|
||||
|
||||
#define N 10000000
|
||||
#define CS N /* cache size */
|
||||
|
||||
typedef unsigned long ulong;
|
||||
ulong cache[CS] = {0};
|
||||
|
||||
ulong hailstone(ulong n)
|
||||
{
|
||||
int x;
|
||||
if (n == 1) return 1;
|
||||
if (n < CS && cache[n]) return cache[n];
|
||||
|
||||
x = 1 + hailstone((n & 1) ? 3 * n + 1 : n / 2);
|
||||
if (n < CS) cache[n] = x;
|
||||
return x;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int i, l, max = 0, mi;
|
||||
for (i = 1; i < N; i++) {
|
||||
if ((l = hailstone(i)) > max) {
|
||||
max = l;
|
||||
mi = i;
|
||||
}
|
||||
}
|
||||
printf("max below %d: %d, length %d\n", N, mi, max);
|
||||
return 0;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue