I've tried to solve "The 3n+1" problem. When I debug my code it stuck at line 12, calculation function. "According to Collatz conjecture, j should converge to 1."
Main file
#include "input_output.h"
#include <stdlib.h>
int main() {
int i=0, j=0;`
int *num;
int maxCycle;
int length;
input(&i, &j);
length = j - i + 1;
num = (int*)malloc(sizeof(int)*(j - i+1));
here is the problem code
while (i <= j) {
calculate(j, num);//<- it stuck at here when i dubug it.
j--;
num++;
}
maxCycle = findMax(length, num);
output(maxCycle);
return 0;
}
source file
#include <stdio.h>
#include "input_output.h"
#pragma warning (disable:4996)
void input(int *i, int *j) {
scanf("%d %d", i,j);
}
void calculate(int j, int* num) {
while (j > 1) {
if (j % 2 == 0) {
j = j / 2;
*num++;
}
if (j % 2 == 1) {
j = j * 3 + 1;
*num++;
}
}
}
int findMax(int length, int * num){
int max = 0;
int idx = 0;
while (idx < length) {
if (*num > max) max = *num;
idx++;
num++;
}
return max;
}
void output(int maxout) {
printf("%d", maxout);
}
Header
#ifndef __input_output_H__
#define __input_output_H__
void input(int *i, int *j);
void calculate(int j,int *num);
int findMax(int length, int* num);
void output(int maxout);
#endif __input_output_H__
I think header seems no problem and also main file. is there any problem with my source file? I wonder why debugger stuck at there...