2014-11-23 93 views
-1

here開始,我試圖開發自己的邏輯來生成一系列醜陋的數字。但每次打印所有數字。C中的醜陋數字的邏輯

我正在確定數字的前3個素數因子是2,3和5,並將它們放置在一個計數變量中,以確定數字x的素數因子總數。

如果計數大於3,數字並不難看。

下面是代碼:

/* To generate a sequence of Ugly numbers 
    Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 
    1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … 
    shows the first 11 ugly numbers. By convention, 1 is included. 
*/ 

#include<stdio.h> 
#include<math.h> 

int isprime(int x) 
{ 
    int i; 
    for(i=2;i<=sqrt(x);i++) 
     if(x%i==0) 
      return 0; 
    return 1; 
} 

int isUgly(int x) 
{ 
    int count=0; //To maintain the count of the prime factors. If count > 3, then the number is not ugly 
    int i; 
    for(i=2;i<=sqrt(x);i++) 
    { 
     if(isprime(i) && x%i==0) 
     { 
      count++; 
      if(count > 3) 
       return 0; // Not ugly 
     } 
    } 
    return 1; 
} 

int main(void) 
{ 
    int i,n=10; 
    printf("\n The ugly numbers upto %d are : 1 ",n); 
    for(i=2;i<=n;i++) 
    { 
     if(isUgly(i)) 
      printf(" %d ",i); 
    } 
    return 0; 
} 
+1

步驟雖然與調試器的代碼。 – 2014-11-23 04:56:21

+1

谷歌搜索'醜陋的數字'出現了[定義](http://www.geeksforgeeks.org/ugly-numbers/):_醜陋的數字是其唯一的主要因素是2,3或5的數字。按照慣例,所以包括1。因此,通過這個定義,如果可以重複(正好)2,然後3,然後5,並且值的序列結束於1,那麼數字會變得很難看。如果它以其他方式結束數字,那麼它不是醜陋的,並且序列中的最後一個值是除2,3或5以外的一個或多個素數的乘積。(谷歌搜索還揭示了關於該主題的一些SO問題。) – 2014-11-23 05:50:42

回答

1

這裏是isUgly()一個版本,這似乎爲我工作。

int isUgly(int x) 
{ 
    int i; 
    static int factors[] = {2, 3, 5}; 

    // Boundary case... 
    // If the input is 2, 3, or 5, it is an ugly number. 
    for (i = 0; i < 3; ++i) 
    { 
     if (factors[i] == x) 
     { 
      return 1; 
     } 
    } 

    if (isprime(x)) 
    { 
     // The input is not 2, 3, or 5 but it is a prime number. 
     // It is not an ugly number. 
     return 0; 
    } 

    // The input is not a prime number. 
    // If it is divided by 2, 3, or 5, call the function recursively. 
    for (i = 0; i < 3; ++i) 
    { 
     if (x%factors[i] == 0) 
     { 
      return isUgly(x/factors[i]); 
     } 
    } 

    // If the input not a prime number and it is not divided by 
    // 2, 3, or 5, then it is not an ugly number. 
    return 0; 
} 
+0

你能稍微解釋一下代碼,如果一個數字超過2,3或5,會發生什麼? – xxx 2014-11-23 05:41:25

+0

它落在最後的'for'循環並返回'0'。 – 2014-11-23 05:42:33

+0

雅得到它。謝謝 :) – xxx 2014-11-23 05:45:28

0

試試這個:

#include<stdio.h> 

long int n, count=1; 

void check(long int i) 
{ 
    if(i==1){ 
     ++count; 
     return; 
    } 
    else if(i%2==0) 
     check(i/2); 

    else if(i%3==0) 
     check(i/3); 

    else if(i%5==0) 
     check(i/5); 
    else 
     return; 
} 

void main(){ 

    for(n=1;;n++){ 

     check(n); 

     if(count==1000){ 
      printf("%ldth no is %ld\n",count,n); 
      break; 
     } 
    } 
}