【问题标题】:number of factors of n that are less than square root of n小于 n 平方根的 n 的因子数
【发布时间】:2016-08-06 17:30:06
【问题描述】:

我想找到一个数的因子数,比如 900,它小于它的平方根。 例如:有 27 个 900 的因子,我想找到小于 900 的根的因子数,即 30,它们是 1、2、3、4、5、6、9、10、12、15、18、20, 25.

我目前有这个程序,它通过计算素因子的数量来找到因子的数量。例如:140 的质因数是:2^2*5*7。所以因数的个数是:(2+1)(1+1)(1+1) [素因数的幂]

import java.io.*;
import java.util.*;
class Solution
{
// Program to print all prime factors
static void primeFactors(int n)
{

    TreeMap tm=new TreeMap();
    int times=0;
    // Print the number of 2s that divide n
    while (n%2 == 0)
    {
        System.out.println("2");
        if(!tm.containsKey(2))
        {
            tm.put(2,1);
        }
        else
        {
            times=(int)tm.get(2);
            tm.put(2,times+1);
        }
        n = n/2;
    }

    // n must be odd at this point.  So we can skip one element (Note i = i +2)
    for (int i = 3; i <= Math.sqrt(n); i = i+2)
    {
        // While i divides n, print i and divide n
        while (n%i == 0)
        {
            System.out.println(i);
            if(!tm.containsKey(i))
            {
                tm.put(i,1);
            }
            else
            {
            times=(int)tm.get(i);
            tm.put(i,times+1);
            }
            n = n/i;
        }
    }

    // This condition is to handle the case whien n is a prime number
    // greater than 2
    if (n > 2)
    {
        System.out.println(n);
        if(!tm.containsKey(n))
        {
            tm.put(n,1);
        }
        else
        {
        times=(int)tm.get(n);
        tm.put(n,times+1);
        }
    }

    /////////////////////////////////////////////////////////////////////////////
    Set set = tm.entrySet();
    System.out.println(tm);
    Iterator num = set.iterator();
    int key=0;
    int sum=1;
    while (num.hasNext())
    {
        Map.Entry number =(Map.Entry)num.next();
        sum=sum*((int)number.getValue()+1);
    }
    System.out.println(sum);
}

public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    primeFactors(n);
}
}

在这里我得到了一些因素,例如:27 个因素代表 900,但我想找到小于 30 个因素的数量。感谢您的帮助。

【问题讨论】:

    标签: java numbers factors


    【解决方案1】:

    如果您有 n 的因子数,只需将整数除以 2 即可得到小于平方根的因子数。这是有效的,因为小于 sqrt(n) 的 n 的每个因子 d 对应一个大于 sqrt(n) 的因子(即 n/d),所以这些因子的数量将是总数的一半(除非 n 是一个完美的平方,在这种情况下 sqrt(n) 是一个额外的因素)。但是,整数除以 2 会处理这种极端情况。确实,27/2 = 13 随心所欲。

    【讨论】:

      猜你喜欢
      • 2013-09-04
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 2021-08-02
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多