Problem : Consider the following algorithm to generate a sequence of numbers. Start with an integer n. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process with the new value of n, terminating when n = 1. The input will consist of a series of pairs of integers i and j, one pair of integers perline. All integers will be less than 1,000,000 and greater than 0. For each pair of input integers i and j, output i, j in the same order in which they appeared in the input and then the maximum cycle length for integers between and including i and j. These three numbers should be separated by one space, with all three numbers on one line and with one line of output for each line of input.
示例输入:
1 10
示例输出:
1 10 20
所以我写了这个:
#include <stdio.h>
#include <string.h>
struct line{int in1;int in2;int result;};
int cycle(int in);
int main(int argc, char *argv[]) {
int cycle(int in);
char c;
int firstIn=0;
struct line l[500] ;
int pointer=0;
while(2<3){
l[pointer].in1=0;
l[pointer].in2=0;
scanf("%u %u",&l[pointer].in1,&l[pointer].in2);
if(l[pointer].in1<1||l[pointer].in2<1){
break;
}
int maxCyc=0;
int j,m;
int min,max;
if(l[pointer].in1>l[pointer].in2){
max=l[pointer].in1;
min=l[pointer].in2;
}
else{
max=l[pointer].in2;
min=l[pointer].in1;
}
for(j=min;j<=max;j++){
m = cycle(j);
if(m>maxCyc)
maxCyc=m;
}
l[pointer].result=maxCyc;
printf("%d %d %d\n",l[pointer].in1,l[pointer].in2,l[pointer].result);
pointer++;
}
}
int cycle(int in){
int cyc = 1;
while(in>1){
if(in%2==0){
cyc++;
in=in/2;
}
else{
cyc++;
in=in*3+1;
}
}
return cyc;
}
完全没问题,但是当您将循环方法中的 while(in>1)
更改为 while(in!=1)
时,它会变得更慢。我的问题是为什么?!
Time when its
while(in>1)
: 0.683 secand when its
while(in!=1)
: I waited more than 5 min nothing happened yet :)for input : 1 1000000
不存在无限循环或其他东西,因为 in
根本无法低于 1(因为它必须已经是 1)。
致以诚挚的问候
最佳答案
当您使用输入值113383
调用cycle
时,该过程最终将n
设置为
827370449,而3*827370449+1为2482111348,大于最大signed int
,解释为-1812855948。所以这是你的第一个负数,而不应该有负数。
如果此过程最终将 n
设置为 -2,则此后它将在 -2 和 -1 之间无限循环。可能还有其他我没有考虑到的循环。
如果您要使用无符号整数,则有可能(我没有检查)最终也会溢出,这不会导致负值,但会导致不正确 值,使您的结果无效。
无论您使用哪种整数表示形式,最好在每个循环的顶部将 n
与 (maximum-1)/3
进行比较,其中 maximum
是整数类型的最大可能正值,只是为了确保不会溢出。
关于c - 为什么 < 比 != 快得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24779137/