2015-11-13 28 views
-5

數字124具有它的前三個倍數包含數字2的最小數字的性質。注意到124 * 1 = 124,124 * 2 = 248,124 * 3 = 372而且124,248和372分別包含數字2.有可能將此屬性推廣爲最小的數字,其前n個數字包含數字2.編寫一個名爲smallest(n)的函數,返回前n個倍數包含數字2.提示:使用模數基10算術來檢查數字。僅用循環求解

它的簽名是 INT最小(INT N)

例子 如果n回報,因爲 4 624,因爲624的前四倍的倍數是624,1248,1872年,2496,它們都含有 位2.此外,624是前四個倍數包含數字2的最小數字。 5 624因爲前6個倍數624是624,1248,1872,2496,3120。請注意,624也是 的最小數字,其前4位倍數包含數字2. 6 642,因爲642的前五個倍數是642,1284,1926,2568,3210,3852,因爲4062的前五個倍數是4062,8124,12186,16248,20310,24372,28434。 請注意,其中一個倍數包含數字2不止一次(例如24372)是可以的。

我試圖通過這種方式

//Its a incomplete code  
public static int smallest(int n) 
      { 
       int i = 1; 
       for (; ;) 
       { 
        int temp = 0; 
        int myNum = 0; 
        for (int j = 1; j <= n; j++) 
        { 
         myNum = i * j; 
         //check for condition 
        } 
        //if condition ture break 
       } 
      } 

解決這個但我堅持到問題是我不能創建硬編碼n次變量..你能幫助我繼續嗎?

你可能會認爲這樣一個數字可以在32位機器上計算出來,也就是說,你不必在你的答案中檢測到整數溢出。

+0

你有沒有退出條件的無限循環。 –

+0

任何人都可以請給我提示?我沒有要求解決方案。只是一個提示怎麼辦? – Brajesh

+0

其不完整的代碼..我正在做.. Ron Beyer。但我不知道如何與n次進行比較..我的意思是你可以給我一個提示 – Brajesh

回答

1
public static int smallest(int n) 
    { 
     int i = 1; 
     for (; ;) 
     { 
      int contain = 0; 
      int temp = 0; 
      int myNum = 0; 
      for (int j = 1; j <= n; j++) 
      { 
       myNum = i * j; 
       temp = myNum; 

       while (true) 
       { 
        if (temp % 10 == 2) 
        { 
         contain++; 
         break; 
        } 

        temp = temp/10; 
        if (temp <= 0) 
         break; 
       } 
      } 
      if (contain == n) 
       break; 
      i++; 

     } 
     return i; 
    } 
0

using System; 
 
using System.Collections.Generic; 
 

 
namespace firstconsoleproject 
 
{ 
 
\t class MainClass 
 
\t { 
 
\t \t public static void Main (string[] args)  
 
\t \t { 
 
\t \t \t int first=4; 
 
\t \t \t int c=0; 
 
\t \t \t int ax; 
 
\t \t \t int ai; 
 
\t \t \t Console.WriteLine ("please enter n"); 
 
\t \t \t ax = Convert.ToInt32(Console.ReadLine()); 
 
\t \t \t for (int i=11 ; ax>0 ;) 
 
\t \t \t { if (first==1) 
 
\t \t \t \t { 
 
\t \t \t \t \t c = ax+1; 
 
\t \t \t \t \t i++; 
 
\t \t \t \t } \t 
 
\t \t \t \t c--; 
 
\t \t \t \t ai=i*c; 
 
\t \t \t \t \t for (int ten=10 ; ;) 
 
\t \t \t \t { \t 
 
\t \t \t \t \t  if(ai%ten==2) 
 
\t \t \t \t \t  { 
 
\t \t \t \t \t \t first=0; \t 
 
\t \t \t \t \t \t break; \t \t \t \t \t \t  
 
\t \t \t \t \t  }else if (ai==0) 
 
\t \t \t \t \t  { 
 
\t \t \t \t \t \t first=1; 
 
\t \t \t \t \t \t break; 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t  ai/=10; 
 
\t \t \t \t  
 
\t \t \t \t } 
 
\t \t \t \t 
 
\t \t \t \t if (c==0){Console.WriteLine("number is "+i);break;} 
 
\t \t \t 
 
\t \t  \t }Console.ReadKey(); 
 

 
\t \t \t \t 
 
\t  } 
 
     } 
 
} 
 
\t 
 
\t 
 
\t \t 
 
\t 
 

 
\t