Java 为数学目的使用循环编程。(爪哇)
让我解释一下这个问题 我需要写一个程序,在其中输入一个数字N,然后我必须找到一个最小的数字,这个数字可以被所有的数字整除到一 例:。如果我的N是5,答案是60。60可以被5,4,3,2和1整除 这是我到目前为止所拥有的Java 为数学目的使用循环编程。(爪哇),java,loops,math,conditional,Java,Loops,Math,Conditional,让我解释一下这个问题 我需要写一个程序,在其中输入一个数字N,然后我必须找到一个最小的数字,这个数字可以被所有的数字整除到一 例:。如果我的N是5,答案是60。60可以被5,4,3,2和1整除 这是我到目前为止所拥有的 import java.util.Scanner; public class Questão_04 { public static void main (String [] args) { int x = 1, n = 1, d = x % n; System
import java.util.Scanner;
public class Questão_04 {
public static void main (String [] args)
{
int x = 1, n = 1, d = x % n;
System.out.print("Enter N: ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
do
{
if (d != 0)
{
x = x + 1;
do
{
n = n -1;
} while (n != 0);
}
else
{
do
{
n = n - 1;
} while (d != 0);
}
} while (n != 0);
System.out.print(x);\\the minimum number divisible by N and all up to N.
}
最后,在绞尽脑汁一段时间后,我终于找到了一个有效的解决方案:
public int smallestMatching(int n){
ArrayList<Integer> divisors = new ArrayList<>();
for(int i = 2 ; i <= n ; i++){
int tmp = i;
//simplify div, until it can't be created by multiplying elements of divisors
for(int div : divisors)
if(tmp % div == 0)
tmp /= div;
if(tmp != 1)
//tmp cant be generated from number that are content of divisors
//-> add to divisors
{
divisors.add(tmp);
}
}
//calculate the final result
int result = 1;
for(int div: divisors)
result *= div;
return result;
}
public int smallestMatching(int n){
ArrayList除数=新的ArrayList();
对于(int i=2;i求该值的有效算法只考虑小于或等于N的素数幂
- 从
v=1开始
- 对于小于或等于
N的素数中的p_i
- 求最大整数
q_i
,这样p_i^q_i我猜你是在试图计算f(n)=lcm(1,2,…,n)
。对于较小的n
,函数似乎增长很快,但我想它最终可能会随着素数的间隔而逐渐变小。理论上说lnf(n)/n
渐近于1
,因此f(n)
大致呈指数增长
我们可以通过注意lcm(1,2,…,n)
=lcm(lcm(1,2,…,n-1),n)
来简化,因此f(n)
可以递归计算。此外,lcm(a,b)=a*b/gcd(a,b)
因此我们可以根据标准gcd
函数编写递归。我建议递归计算f
如下:f
(n+1)=f(n)/gcd(f(n),n+1)*(n+1)
。在相乘之前进行除法可以使中间结果的大小保持较小。gcd
将f(n)
均匀地除法,因此整数除法很好。您可以通过记住f(n)
来加快计算速度,但如果您只计算f(n),则没有帮助
一个n
我已经用Java实现了下面的函数。它以我所能达到的速度运行,至少直到堆栈大小溢出为止,在我的计算机上大约n=10000
。您可以重新组织以使用迭代而不是递归,这可能会推高最大n
。(基于类似的情况,我猜我的计算机上大约有n=50000
内存不足,但我还没有真正尝试过。)
好的,我终于找到了一个正确且非常有效的答案。顺便说一句,这是一个很好的问题。我花了一些时间。^^事实上,如果您在运行时生成素数,代码会更加高效、更短,并且需要更少的表(我已经尝试了这两种解决方案)。我知道我以前已经回答过类似的问题:这里是前面的答案,提供了更多信息(虽然用python…)
import java.math.BigInteger;
public class LCM {
public static BigInteger f(int n) {
if (n == 1) return BigInteger.ONE;
BigInteger prev = f(n-1);
return prev.divide(prev.gcd(BigInteger.valueOf(n)))
.multiply(BigInteger.valueOf(n));
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
System.out.println("f(" + n + ") = " + f(n));
}
}