【问题标题】:Finding the smallest integer that is a factor of C?找到作为 C 因子的最小整数?
【发布时间】:2012-09-14 07:17:16
【问题描述】:

我需要有关此方法的帮助 最小因子

public static int smallestFactor(int C) 此函数将整数 C 作为其参数,它返回除 1 以外的 C 的因子的最小整数。

参数: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;
    }
}

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

【问题讨论】:

  • 你打印的第一个 i 就是它。
  • 此函数以递增顺序打印所有因子。因此,只需在打印后的 while 中添加 break 语句即可。

标签: java numbers factorization


【解决方案1】:

您需要使用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;
}

您还可以进行其他改进,但这应该可以帮助您入门。

【讨论】:

    【解决方案2】:

    对您的代码进行一些小改动 - 您已经接近了!

    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;
        }
    }
    

    【讨论】:

      【解决方案3】:

      处理所有异常情况,试试这个代码:

      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.
      }
      

      【讨论】:

        【解决方案4】:

        您需要返回的值是您的i,而不是C

        您应该在循环中处理i 的可能值,并在找到C % i == 0 时处理return 的值。

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

        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
        }
        

        事实上,最有效的算法只会测试素数因子,但我怀疑这超出了你被问到的范围。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-11-08
          • 2022-08-10
          • 2011-02-07
          • 1970-01-01
          • 2017-11-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多