为什么下面的代码会永远运行?

时间:2011-11-22 11:27:11

标签: c++ algorithm

我无法理解为什么下面的代码会永远运行:

#include <cstdlib>
#include <iostream>
#include<iostream>
#define in_least_terms(n,d) (gcd((n),(d))==1)
using namespace std;

unsigned int gcd(unsigned int  x,unsigned int y){
    while(y!=0){
        unsigned int t=y;
        y=x%y;
        x=t; 
    }     
    return x;
}

void generate()
{
    unsigned int sum,numerator,denominator;
    printf("0\n");
    for(sum=2;sum<2000;sum++){
        for(numerator=1;numerator<=sum-1;numerator++){
        denominator=sum-numerator;
        if(denominator==1)
            printf(" %u]n-%u\n",numerator,numerator);
        else if((in_least_terms(  numerator,denominator)))
            printf("%u/%u\n-%u/%u\n", numerator, denominator, numerator, denominator);                                                 
        }                             
    }       
}

int main(int argc, char *argv[])
{
    generate();
    system("PAUSE");
    return EXIT_SUCCESS;
}

我找不到有什么问题。请帮帮我。

1 个答案:

答案 0 :(得分:2)

它不会“永远”运行它只需花费很长的时间来完成任务......据我所知,你有内部循环的-1+n*(n+1)/2次迭代,在你的情况下是200999次! printf-method需要一段时间才能将所有内容打印到屏幕上!

如果你运行下面的代码(从输出中去掉以澄清循环维度),你会看到内循环的每个循环迭代都打印了一个x ...如你所见,它是很多x的...也许内环的边界有问题吗?

#include <cstdlib>
#include <iostream>
#include<iostream>
#include <cstdio>
#define in_least_terms(n,d) (gcd((n),(d))==1)
using namespace std;

unsigned int gcd(unsigned int  x,unsigned int y){
    while(y!=0){
        unsigned int t=y;
        y=x%y;
        x=t; 
    }     
    return x;
}

void generate()
{
    unsigned int sum,numerator,denominator;
    printf("0\n");
    for(sum=2;sum<2000;sum++){
        for(numerator=1;numerator<=sum-1;numerator++){
            printf("x");
            denominator=sum-numerator;
            if(denominator==1){}
            else if((in_least_terms( numerator,denominator))){}                                        
        }                             
    }       
}

int main(int argc, char *argv[])
{
    generate();
    system("PAUSE");
    return EXIT_SUCCESS;
}