[英]Determine factors of a number (n), then return possible pairs of positive integers that when multiplied together are less than (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.