程式設計之美2 8 找符合條件的整數

2021-06-07 10:27:05 字數 1510 閱讀 8794

問題:

任意給定乙個正整數n,求乙個最小的正整數m(m>1),使得n*m的十進位制表示形式裡只含有1和0。

解法:

由於沒有直接的數學方法能幫我們直接得到m的值,所以我們只能進行搜尋。由於相對m,乘積n*m具有明顯的特徵,需要搜尋的空間要小很多,所以我們對乘積n*m進行搜尋。如果n*m的結果有k位,則要迴圈2^k次,我們發現k的結果能輕易超過40,所以這個執行時間還是相當長。

同餘運算具有等價關係,mod n = i(0<=i

我們可以證明對於任意的n,一定存在m,使得n*m的乘積的十進位制表示只有0和1。證明過程見

由於無論m還是n*m的位數都相當大,所以我們用大整數表示m和n*m。由於要n個大整數,所以n不能為大整數,即其值最好取一百萬以內。

#include #include using namespace std;

// 大整數型別

#define maxlen 100

struct hp ;

void printhp(const hp &x)

// 字串轉大整數

void str2hp(const char *s, hp &x)

}// 大整數的加法

void plus(const hp a, const hp b, hp &c)

// 退出迴圈到原因是c.s[i]==0,所以取前一位

c.len = i-1;

if (c.len == 0) c.len = 1;

}// 大整數的減法

void subtract(const hp a, const hp b, hp &c)

else j = 0;

} c.len = a.len;

while (c.len > 1 && !c.s[c.len]) c.len--;

}// 大整數的比較

int hpcompare(const hp &x, const hp &y)

// 大整數的乘法

void multi(const hp a, const hp b, hp &c)

// 大整數的除法

void divide(const hp a, const hp b, hp &c, hp &d)

d.s[1] = a.s[i];

c.s[i] = 0;

// 餘數d大於除數b時,才可以進行減操作

while ((j=hpcompare(d,b)) >= 0)

}c.len = a.len;

while (c.len > 1 && c.s[c.len] == 0)

c.len--;

}// 十進位右移

void rightshift(hp &x, int k)

}// 十進位左移

void leftshift(hp &x, int k)

#define maxrem 1000000

hp rem[maxrem];

int main()

// 清空餘數資訊陣列

for (i=0; i

程式設計之美2 8 找符合條件的整數

這個題目是,給定乙個整數 n,需要尋找另外乙個整數 m,使得 n m 得到的結果十進位制表示中只存在1和0兩個數字。首先看到這個題目,第一思想肯定是 使 m 1,並依此遞增 m 的值,直到 n m 獲得想要的效果,但是,如果 n 很大呢,那麼計算量也是很大的,所以,我們需要尋求更好的解決辦法。書中提...

程式設計之美2 8 找符合條件的整數

書上面講的很好,程式也寫得很巧妙。最主要的一句話 只需要將10k n的結果與餘數資訊陣列裡非空的元素相加,再去模n,看看會不會出現新的餘數。include include using namespace std vectorfind number int n bigint 1 push back 0...

程式設計之美2 8找符合條件的整數

問題 任意給定乙個正整數n,求乙個最小的正整數m m 1 使得n m的十進位制表示形式裡只含有1和0。思路 建立模n的餘數記錄表,通過動態規劃的思想找到相應的m 例子 當n 3時 record110 1000 111112 11 當j 1時,j n 1,更新record。當j 10時,j n 1存在...