java公约数_Java:获得最大的公约数
Java:获得最大的公约数
我已经看到BigInteger#gcd(即BigInteger#gcd)存在这样的功能。Java中是否还有其他功能也可用于其他类型(int、long或Integer)? 看起来这像java.lang.Math.gcd(带有各种重载)是有意义的,但它不存在。 在别的地方吗?
(请不要将此问题与“我自己如何实现”混淆!)
16个解决方案
124 votes
据我所知,没有任何内置的基元方法。 但是像这样简单的事情应该可以解决问题:
public int GCD(int a, int b) {
if (b==0) return a;
return GCD(b,a%b);
}
如果您喜欢这种事情,也可以单行处理:
public int GCD(int a, int b) { return b==0 ? a : GCD(b, a%b); }
应该注意的是,两者编译成相同的字节码时,绝对没有区别。
Matt answered 2019-09-22T02:48:25Z
67 votes
对于int和long而言,作为原语,并非如此。 对于Integer,可能有人写过一个。
鉴于BigInteger是int,Integer,long和Long的(数学/函数)超集,如果您需要使用这些类型,请将其转换为BigInteger,执行GCD,然后将结果转换回。
private static int gcdThing(int a, int b) {
BigInteger b1 = BigInteger.valueOf(a);
BigInteger b2 = BigInteger.valueOf(b);
BigInteger gcd = b1.gcd(b2);
return gcd.intValue();
}
Tony Ennis answered 2019-09-22T02:47:45Z
33 votes
或用于计算GCD的欧几里得算法...
public int egcd(int a, int b) {
if (a == 0)
return b;
while (b != 0) {
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
Xorlev answered 2019-09-22T02:48:51Z
11 votes
使用番石榴LongMath.gcd()和IntMath.gcd()
Morad answered 2019-09-22T02:49:17Z
11 votes
雅加达公共数学就是这样。
ArithmeticUtils.gcd(int p,int q)
Tom Tucker answered 2019-09-22T02:49:53Z
9 votes
除非我有番石榴,否则我会这样定义:
int gcd(int a, int b) {
return a == 0 ? b : gcd(b % a, a);
}
Alexey answered 2019-09-22T02:50:18Z
6 votes
您可以使用Binary GCD算法的此实现
public class BinaryGCD {
public static int gcd(int p, int q) {
if (q == 0) return p;
if (p == 0) return q;
// p and q even
if ((p & 1) == 0 && (q & 1) == 0) return gcd(p >> 1, q >> 1) << 1;
// p is even, q is odd
else if ((p & 1) == 0) return gcd(p >> 1, q);
// p is odd, q is even
else if ((q & 1) == 0) return gcd(p, q >> 1);
// p and q odd, p >= q
else if (p >= q) return gcd((p-q) >> 1, q);
// p and q odd, p < q
else return gcd(p, (q-p) >> 1);
}
public static void main(String[] args) {
int p = Integer.parseInt(args[0]);
int q = Integer.parseInt(args[1]);
System.out.println("gcd(" + p + ", " + q + ") = " + gcd(p, q));
}
}
来自[http://introcs.cs.princeton.edu/java/23recursion/BinaryGCD.java.html]
linuxjava answered 2019-09-22T02:50:52Z
6 votes
如果两个数字均为负,则此处的某些实现将无法正常工作。 gcd(-12,-18)是6,而不是-6。
因此,应该返回一个绝对值,例如
public static int gcd(int a, int b) {
if (b == 0) {
return Math.abs(a);
}
return gcd(b, a % b);
}
Robot Monk answered 2019-09-22T02:51:25Z
3 votes
我们可以使用递归函数来查找gcd
public class Test
{
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Driver method
public static void main(String[] args)
{
int a = 98, b = 56;
System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
}
}
Esann answered 2019-09-22T02:51:51Z
2 votes
如果使用Java 1.5或更高版本,则这是一个迭代的二进制GCD算法,它使用Integer.numberOfTrailingZeros()减少所需的检查和迭代次数。
public class Utils {
public static final int gcd( int a, int b ){
// Deal with the degenerate case where values are Integer.MIN_VALUE
// since -Integer.MIN_VALUE = Integer.MAX_VALUE+1
if ( a == Integer.MIN_VALUE )
{
if ( b == Integer.MIN_VALUE )
throw new IllegalArgumentException( "gcd() is greater than Integer.MAX_VALUE" );
return 1 << Integer.numberOfTrailingZeros( Math.abs(b) );
}
if ( b == Integer.MIN_VALUE )
return 1 << Integer.numberOfTrailingZeros( Math.abs(a) );
a = Math.abs(a);
b = Math.abs(b);
if ( a == 0 ) return b;
if ( b == 0 ) return a;
int factorsOfTwoInA = Integer.numberOfTrailingZeros(a),
factorsOfTwoInB = Integer.numberOfTrailingZeros(b),
commonFactorsOfTwo = Math.min(factorsOfTwoInA,factorsOfTwoInB);
a >>= factorsOfTwoInA;
b >>= factorsOfTwoInB;
while(a != b){
if ( a > b ) {
a = (a - b);
a >>= Integer.numberOfTrailingZeros( a );
} else {
b = (b - a);
b >>= Integer.numberOfTrailingZeros( b );
}
}
return a << commonFactorsOfTwo;
}
}
单元测试:
import java.math.BigInteger;
import org.junit.Test;
import static org.junit.Assert.*;
public class UtilsTest {
@Test
public void gcdUpToOneThousand(){
for ( int x = -1000; x <= 1000; ++x )
for ( int y = -1000; y <= 1000; ++y )
{
int gcd = Utils.gcd(x, y);
int expected = BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue();
assertEquals( expected, gcd );
}
}
@Test
public void gcdMinValue(){
for ( int x = 0; x < Integer.SIZE-1; x++ ){
int gcd = Utils.gcd(Integer.MIN_VALUE,1<
int expected = BigInteger.valueOf(Integer.MIN_VALUE).gcd(BigInteger.valueOf(1<
assertEquals( expected, gcd );
}
}
}
MT0 answered 2019-09-22T02:52:23Z
1 votes
public int gcd(int num1, int num2) {
int max = Math.abs(num1);
int min = Math.abs(num2);
while (max > 0) {
if (max < min) {
int x = max;
max = min;
min = x;
}
max %= min;
}
return min;
}
此方法使用Euclid的算法来获取两个整数的“最大公约数”。 它接收两个整数并返回它们的gcd。 就这么简单!
Mohsen answered 2019-09-22T02:52:49Z
0 votes
/*
import scanner and instantiate scanner class;
declare your method with two parameters
declare a third variable;
set condition;
swap the parameter values if condition is met;
set second conditon based on result of first condition;
divide and assign remainder to the third variable;
swap the result;
in the main method, allow for user input;
Call the method;
*/
public class gcf {
public static void main (String[]args){//start of main method
Scanner input = new Scanner (System.in);//allow for user input
System.out.println("Please enter the first integer: ");//prompt
int a = input.nextInt();//initial user input
System.out.println("Please enter a second interger: ");//prompt
int b = input.nextInt();//second user input
Divide(a,b);//call method
}
public static void Divide(int a, int b) {//start of your method
int temp;
// making a greater than b
if (b > a) {
temp = a;
a = b;
b = temp;
}
while (b !=0) {
// gcd of b and a%b
temp = a%b;
// always make a greater than b
a =b;
b =temp;
}
System.out.println(a);//print to console
}
}
Gitau Harrison answered 2019-09-22T02:53:08Z
0 votes
我使用了14岁时创建的这种方法。
public static int gcd (int a, int b) {
int s = 1;
int ia = Math.abs(a);//
int ib = Math.abs(b);
if (a == b) {
s = a;
}else {
while (ib != ia) {
if (ib > ia) {
s = ib - ia;
ib = s;
}else {
s = ia - ib;
ia = s;
}
}
}
return s;
}
John Doe answered 2019-09-22T02:53:33Z
0 votes
在别的地方吗?
Apache的! -它同时具有gcd和lcm,太酷了!
但是,由于其实现的深刻性,与简单的手写版本相比(如果重要),它的速度较慢。
Boleslovas Švitrigaila answered 2019-09-22T02:54:13Z
0 votes
Commons-Math和Guava提供的GCD功能有所不同。
Commons-Math仅对IllegalArgumentException.class或Long.MIN_VALUE抛出ArithematicException.class。否则,将该值作为绝对值处理。
番石榴会为任何负值抛出IllegalArgumentException.class。
Jin Kwon answered 2019-09-22T02:55:02Z
-3 votes
%将给我们的gcd在两个数字之间,它表示:-big_number / small_number的%或mod为= gcd,并且我们在Java上将其编写为big_number % small_number。
EX1:两个整数
public static int gcd(int x1,int x2)
{
if(x1>x2)
{
if(x2!=0)
{
if(x1%x2==0)
return x2;
return x1%x2;
}
return x1;
}
else if(x1!=0)
{
if(x2%x1==0)
return x1;
return x2%x1;
}
return x2;
}
EX2:三个整数
public static int gcd(int x1,int x2,int x3)
{
int m,t;
if(x1>x2)
t=x1;
t=x2;
if(t>x3)
m=t;
m=x3;
for(int i=m;i>=1;i--)
{
if(x1%i==0 && x2%i==0 && x3%i==0)
{
return i;
}
}
return 1;
}
Mr-Al7lawe answered 2019-09-22T02:55:43Z
java公约数_Java:获得最大的公约数相关推荐
- c语言怎样求最大公约数,c语言求最大公约数
求差判定法. 如果两个数相差不大,可以用大数减去小数,所得的差与小数的最大公约数就是原来两个数的最大公约数.例如:求78和60的最大公约数.78-60=18,18和60的最大公约数是6,所以78和60 ...
- 【源码+教程】Java课设项目_12款最热最新Java游戏项目_Java游戏开发_Java小游戏_飞翔的小鸟_王者荣耀_超级玛丽_推箱子_黄金矿工_贪吃蛇
马上就要期末了,同学们课设做的如何了呢?本篇为大家带来了12款热门Java小游戏项目的源码和教程,助力大家顺利迎接暑假![源码+教程]Java课设项目_12款最热最新Java游戏项目_Java游戏开发 ...
- 黑马程序员全套Java教程_Java基础教程_异常(含扩展)(二十三)
黑马程序员全套Java教程_Java基础教程_异常(含扩展)(二十三) 1.1 异常概述与异常体系结构 1.2 JVM遇到异常时的默认处理方案 1.3 异常处理 1.4 异常处理之try--catch ...
- java 最小公倍数_Java求最大公约数和最小公倍数
1. 最大公约数(Greatest Common Divisor(GCD)) 1.1 基本概念 最大公因数,也称最大公约数.最大公因子,指两个或多个整数共有约数中最大的一个.a,b的最大公约数记为(a ...
- java求最大公约数_java求最大公约数(分解质因数)
下面是四种用java语言编程实现的求最大公约数的方法: package gcd; import java.util.ArrayList; import java.util.List; public c ...
- java编写最大公约数_Java编写最大公约数和最小公倍数
package javaapplication24; class NegativeIntegerException extends Exception{ String message; public ...
- java编程求最小公约数_java求最大公约数与最小公倍数
public class Gongyueshu { public static void main(String[] args) { //从控制台输入两个数据 int m = Integer.pars ...
- C语言实验——最小公倍数和最大公约数_JAVA
Description 从键盘输入两个正整数,求这两个正整数的最小公倍数和最大公约数,并输出. Input 输入包括一行. 两个以空格分开的正整数. Output 两个整数的最小公倍数和最大公约数. ...
- 每天一段java代码-------第16天(最大公约数最小公倍数)
求指定两个数的最大公约数和最小公倍数 package test; import java.util.Scanner; //求指定两个数的最大公约数和最小公倍数 public class test17 ...
最新文章
- 怎么把圆角变直角_明式圆角柜的还原(下)——信民木工DIY达人大赛作品
- TReader高速文本浏览器 1.0 发布
- ArduinoYun教程之ArduinoYun硬件介绍
- Java面向对象--小游戏2
- python中面向对象的ui_python中面向对象
- [Python] Django+Apache 报 [wsgi:error]问题解决
- 并行算法设计与性能优化_MySQL高性能优化规范建议,从设计,命名,开发等一条线的建议...
- win7中计算机被改为了句号,WIN7中中文输入法快捷键无法修改的解决方法.doc
- vos3000下载java_VOS3000 安装
- python读取tiff文件_怎么用python读取和写入TIFF文件1
- 安卓studio 连接雷电模拟器的历程
- 蓝光三维扫描仪用于无人机结构外壳虚拟装配
- 拼图游戏 java_Java拼图游戏源码
- C++继承问题(白兰花例)
- Git 常用提交操作步骤
- 139邮箱无法验证服务器,139邮箱无法登陆原因,怎么登录自己的139邮箱
- RS Meet DL(68)-建模多任务学习中任务相关性的模型MMoE
- Jupyter使用技巧+快捷键【速查手册】
- 数字化的一切都会在安全沙箱里面
- 超详细Docker部署SpringBoot+Vue项目(三更博客项目部署)
热门文章
- 【英语学习】【Daily English】U14 Transportation L01There will be a car exhibition next month
- Horizon8基础环境准备08——CA证书
- linux g++ undefined reference to `dlopen'类问题
- swagger 修改dto注解_一文搞懂Swagger,让你明白用了Swagger的好处!!!
- sqlite 模糊匹配日期_SQLite模糊查找(like) | 学步园
- linux下安装wls1036_generic.jar,weblogic 安装
- java list 改变变量的值_3、list改变指针还是改变值
- UE4 间接光照缓存
- 《需求工程》阅读笔记之三
- jquery判断toggle当前状态