[英]print out all the numbers between user input and condition that are divisible by 2 and 3. while loop ask for another number
[英]Figure out if a very large number is divisible by another
我正在處理一個編程問題,我需要將一個非常大的數字(10^50000 的數量級)除以 1000 的數量級,以確定一個是否可以被另一個整除。 所以我需要使用字符串來存儲這個大數字。
我不知道將字符串除以數字的任何方法。 誰能指出我的算法?
這是一個算法的開始。 它似乎可以滿足您的要求:它在 4 個字符塊中執行“長除法”,並跟蹤其余部分。 它在最后打印余數。 您應該能夠根據您的特定需求進行調整。 注意 - 在 4 字節塊中執行此操作使其比傳統的一次一個字符算法要快得多,但它確實依賴於b
足夠小以適合int
(因此是 4 個字符塊)。
#include <stdio.h>
#include <string.h>
int main(void) {
char as[]="123123123123126";
int l = strlen(as);
int rem;
int lm = l % 4; // the size of the initial chunk (after which we work in multiples of 4)
char *ap=as; // a pointer to keep track of "where we are in the string"
int b=123; // the divisor
int a;
sscanf(ap, "%4d", &a);
while(lm++ < 4) a /= 10;
// printf("initial a is %d\n", a);
rem = a % b;
for(ap = as + (l%4); ap < as + l; ap += 4) {
// printf("remainder = %d\n", rem);
sscanf(ap, "%4d", &a);
// printf("a is now %d\n", a);
rem = (a + 10000*rem) %b;
}
printf("remainder is %d\n", rem);
return 0;
}
輸出:
remainder is 3
這需要一些清理,但我希望你明白。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.