2015-04-23 85 views
-3

我寫了這個算法來檢查一個數是否是素數,以及哪個數字將其分開。現在我想知道什麼是600851475143除數(例如),並輸出一個負數。 這是我的代碼:如何操縱C中的大數字?

#include <stdio.h> 
/* Discover what numbers divide the one read as input, then show if it's prime */ 

int main() { 
    long checker; 
    long step = 1; 
    int divisors = 0; 

    printf("Enter with the number you want know the divisors: "); 
    scanf("%d", &checker); 
    while(step <= checker){ 
     /* check which numbers divide the number read*/ 
     if (checker % step == 0) { 
      printf("%d divides %d\n", step, checker); 
      step +=1; 
      divisors +=1; 
      } 
      else{ 
       step+=1; 
       } 
    } 

    /*Now check if it is prime*/ 
    if (divisors == 2) { 
     printf("ADDITIONAL INFO: %d IS a prime number.\n", checker); 
    } 
    else { 
     printf("ADDITIONAL INFO: %d IS NOT a prime number.\n", checker); 
    } 
    printf("Done!\n"); 

    return 0; 
} 
+0

有趣的是,人們甚至沒有讀我之前downvoting我。我已經在使用長型變量。 –

回答

1

的問題是,你scanflong使用格式字符串%d這需要一個int變量的地址。您使用printf的方式也是如此。

您需要在格式字符串中將%d替換爲%ld。 你基本上需要這樣做,因爲intlong的大小不相等。

編輯:GCC使用-Wall選項指出錯誤。

+0

剛剛有時間檢查它,但我嘗試用'%ld'格式化程序替換所有'%d'格式化程序,但程序仍然打印負值。 –

+0

@EzequielBarbosa你一定已經忘記了一些。我測試了它。 – Unda

+0

@EzequielBarbosa請注意,如果您使用的是32位機器,那麼您的'600851475143'值對於long來說很大(這將會是4個字節長) – Unda