试图找出Util类中的类和方法声明java
问题描述:
我一直有一些问题试图解决我的教授发送给我的用于学习目的的代码。我通常可以解决isPrime和getPrime没问题,但我的问题在于gcd类。很想得到一些关于这方面的意见。谢谢:)很抱歉的格式,因为我是新来的网站试图找出Util类中的类和方法声明java
import java.util.*;
public class Util3
{
public ??? getSmaller(???)
{
int smaller;
if (???)
smaller = ???;
else
smaller = ???;
return smaller;
}
public ??? gcd(??? a, ??? b)
{
int g, smaller;
smaller = ???(a, b);
g = smaller;
for (int i = ???; i >= 1; i++) { // from smaller to 1
if (a % i == 0 ??? ???) {
g = i;
???;
}
}
return g;
}
public ??? isPrime(int p)
{
if (p < 2)
return false;
int i;
for (i = ???; i <= ???; i++) // from 2 to p-1
if (??? == 0) // if p is divisible by i
break;
if (i == ???)
return ???;
else
return ???;
}
public ??? getPrime(int n)
{
boolean b;
int p;
for (p = n+1; ; p++) { // n+1, n+2, ...
b = ???(p); // check if p is a prime number
if (???)
break;
}
return p;
}
}
答
您可以使用一个天真的解决方案:
public static int gcd(int a, int b) {
int current_gcd = 1;
for(int d = 2; d <= a && d <= b; ++d) {
if (a % d == 0 && b % d == 0) {
if (d > current_gcd) {
current_gcd = d;
}
}
}
return current_gcd;
}
或者递归之一:
public static int GCD(int a, int b) {
if (b == 0) {
return a;
}
}
return GCD(b, a % b);
}
感谢输入!那么非静态方法呢?它肯定有更好的效果,但我现在在单元中的地方还没有需要类中涉及的静态方法。 – Kowalchu1
只需删除static关键字并在Main方法中创建一个Util3实例 – Nooblhu