2012-09-14 33 views
1

我需要用这种方法 smallestFactor找到是C因子的最小整数?

public static int smallestFactor(int C) 此功能作为其参数的整数C,它返回是C的因子的最小整数,大于1

参数其他帮助:C - 一个整数因子。

前提条件:C必须大于1。

返回:C.

的最小因子
public class Factor 
{  
public static long smallestFactor(int C) 
    { 
    for (int i = 2; i*i<= C; i++) 
    { 
     while (C % i == 0) 
     { 
     System.out.print(i + " "); 
     C = C/i; 
     } 
    } 
     return C; 
    } 
} 

我需要找到最小的因子 ,但我不知道该怎么办呢

+0

您打印是它的第一个我。 – njzk2

+0

此功能以升序排列权打印所有因素。所以,只需在打印之后添加一个'break'语句即可。 – Balanivash

回答

5

如果您发现它,则需要使用if而不是while,并返回i

public static long smallestFactor(int C) 
{ 
    for (int i = 2; i*i<= C; i++) 
    { 
     if (C % i == 0) 
     { 
      return i; 
     } 
    } 

    return C; 
} 

还有其他一些可以改进的地方,但是应该让你开始。

0

对代码的小改动 - 您已经接近!

public class Factor { 

    public static long smallestFactor(int C) { 

     for (int i = 2; i*i<= C; i++) { 
      if (C % i == 0) return i; 
     } 
     return -1; 
    } 
} 
+0

返回'-1'不正确,'C'总是自分。 – verdesmarald

+0

我站好了 – AJcodez

0

你需要返回的值是你的i,不C

您应该通过循环中的ireturn可能的值,当您发现C % i == 0时值。

请注意,为了提高效率,您应该测试2,3,然后测试每个奇数。有(4,6,8,...)如果你已经测试了2没有点测试:

public static int smallestFactor(int C) { 
    if (C % 2 == 0) return 2; // C is even 

    for (int i = 3; i * i <= C; i += 2) { 
     if (C % i == 0) return i; // odd factor found 
    } 

    return C; // no factor found 
} 

其实最有效的算法将只对因素考验,但我怀疑这是超出范围你被问过什么。

0

处理所有的特殊情况下,试试这个代码:

public static long smallestFactor(int x) 
{ 
    if(x < 1) return -1; 
    if(x == 1) return 1; 

    for(int i=2; i<=x; i++) 
     if(x % i == 0) 
      return i; 

    return -1; // To stop compiler's complaints. 
}