gpt4 book ai didi

java - 有效数字 - 适当除数的算术平均值不大于该数字的根

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:23 26 4
gpt4 key购买 nike

这个任务看起来很简单 - 在输入时我得到测试数量 (numOfTests),然后是两个数字 (downBorder, upBorder) 和我必须找出这些数字(downBorderupBorder)之间有多少数字是有效数字,其中有效数字是适当除数(除了 1 和之外的所有除数)的算术平均值相同的数字)小于或等于该数字的平方根。我写了代码,可能它能工作,但它太慢了。我的代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
public static void main(String[] args) throws java.lang.Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); //faster than Scanner
int numOfTests = Integer.parseInt(bf.readLine());
for(int i = 0; i < numOfTests; i++)
{
String[] borders = bf.readLine().split(" ");
long downBorder = Long.parseLong(borders[0]);
long upBorder = Long.parseLong(borders[1]);
//System.out.println(String.format("down: %s, up: %s", downBorder, upBorder));
System.out.println(countNumberOfSignificantNumbers(downBorder, upBorder));
}
}

/**
* print numbers of significant numbers - (arithmetic average of all divisors that is not bigger than root of that number)
* e.g 4 is significant but 6 is not
* @param downBorder
* @param upBorder
*/
private static int countNumberOfSignificantNumbers(Long downBorder, Long upBorder) {
int numberOfSignificantNumbers = 0;
for(Long i = downBorder; i <= upBorder; i++)
{
if(i%2 != 0)
continue;
else
{
double avgOfProperDivisors = getAvgArithOfSumOfNumberDividers(i);
if(avgOfProperDivisors != 0 && avgOfProperDivisors <= Math.sqrt(i))
numberOfSignificantNumbers++;
}
}
return numberOfSignificantNumbers;
}

/**
* method returns the arithemtic average of all proper divisors (all divisors except one and number itself)
* @param number
* @return
*/
public static double getAvgArithOfSumOfNumberDividers(Long number)
{
long maxD = number/2;
long sum=0;
long numOfDivs = 0;
for(long i = 2; i <= maxD; i++)
{
if(number % i == 0)
{
numOfDivs++;
sum += i;
}
}
return (numOfDivs > 0) ? (double)sum/numOfDivs : 0;
}
}

此任务的瓶颈在于计算除数的平均值。我怎样才能让它变得更好更快?

Example input:
2
4 6
1 3

Example output:
1
0

最佳答案

Significant Number 永远是质数的完美平方,例如 4、9、25、49、121 等。您需要检查的是 upBorder 之间有多少个质数的完美平方> 和 downBorder

关于java - 有效数字 - 适当除数的算术平均值不大于该数字的根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52399087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com