愛因斯坦出了一道這樣的數學題:有一條長階梯,若每步跨2階,則最最後剩一階,若每步跨3 階,則最後剩2階,若每步跨5階,則最後剩4階,若每步跨6階則最後剩5階。只有每次跨7階,最後才正好一階不剩。請問這條階梯共有多少階。
兩種方法:
方法1:從1開始逐個累增進行實驗
unsigned int GetStairNum (){for(unsigned int n = 1; ;++n){if((1 == n % 2) && (2 == n % 3) && (4 == n % 5) && (5 == n % 6) && (0 == n % 7))return n;}}或者:
unsigned int GetStairNum () { unsigned int StairNum = 0; int flag=1; while(flag) { if(StairNum%2 ==1 && StairNum%3 ==2 && StairNum%5 == 4 && StairNum%6 == 5 && StairNum %7 == 0) { flag =0; return StairNum; } StairNum++; } return 0; } 方法二: 樓梯階數為一個奇數,且是7的倍數,故可以每步跨14(7+14才是奇數,7+7是偶數),進行一個迴圈
unsigned int GetStairNum (){int n = 7;while(1){if((1 == n % 2) && (2 == n % 3) && (4 == n % 5) && (5 == n % 6))return n;elsen += 14;}}
或者:
unsigned int GetStairNum (){unsigned int n = 7;while((1 != n % 2) || (2 != n % 3) || (4 != n % 5) || (5 != n % 6))n += 14;return n;}