繁体   English   中英

小于n的平方根的n的因数

[英]number of factors of n that are less than square root of n

我想找到小于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);
}
}

在这里,我得到许多因素,例如:900的27个因素,但是我想找到小于30的因素。谢谢您的帮助。

如果因子数为n,则将整数除以2即可得到小于平方根的因子数。 之所以可行,是因为n小于sqrt(n)的每个因子d都对应于大于sqrt(n)的因子(即n / d),因此此类因子的数量将为总数的一半(除非n是理想平方,在这种情况下,sqrt(n)是一个额外的因素)。 但是,将整数除以2会解决这种情况。 实际上,根据需要,27/2 = 13。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM