愛因斯坦 上樓梯問題 若每步跨2階,剩1階 兩種方法

來源:互聯網
上載者:User

愛因斯坦出了一道這樣的數學題:有一條長階梯,若每步跨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;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.