2013-05-19 108 views
0

下面是我的代碼,我無法按照它應有的方式工作。確定一個數字是否包含特定的素數因子

我必須找到素數(這工作正常)。然後,如果質數是7和3,則該數字是神奇的,並且如果其包含任何其他數字(98 = 7 * 7 * 242 = 7 * 3 * 2),則不是。

我有種陷在這裏:

if (b != 7 && b != 3) 

         Console.WriteLine(k); 
else 
         Console.WriteLine(j); 

我不知道如何解決它。這裏是整個代碼:

  string k="isnt magical"; 
     string j = "is magical"; 
     int a, b; 
     Console.WriteLine("Vnesite svoje stevilo: "); 
     a = Convert.ToInt32(Console.ReadLine()); 
     for (b = 2; a > 1; b++)/ 
      if (a % b == 0) 
      { 

       while (a % b == 0) 
       { 
        a /= b; 

       } 


       if (b != 7 && b != 3) 
        Console.WriteLine(k); 
       else 
        Console.WriteLine(j); 
     } 

回答

0

您打印"isnt magical""is magical"每一個因素。您的代碼應如下所示:

string k = "isnt magical"; 
string j = "is magical"; 
int a, b; 
Console.WriteLine("Vnesite svoje stevilo: "); 
a = Convert.ToInt32(Console.ReadLine()); 

var allMagical = true; 
for(b = 2; a > 1; b++) if(a % b == 0) 
{ 
    while(a % b == 0) a /= b; 
    if(b != 7 && b != 3) allMagical = false; 
} 

Console.WriteLine(allMagical ? j : k); 
相關問題