java 如何判断两个数是否互质?

xe55xuns  于 2023-04-04  发布在  Java
关注(0)|答案(3)|浏览(317)

我正在尝试写一个方法来计算两个数字是否是相对素数的赋值。我主要是在寻找从哪里开始的答案。我知道有一个方法gcd()可以为我做很多事情,但是赋值几乎让我在没有gcd或数组的情况下做它。
我已经开始了,因为我知道我必须在for循环中使用%运算符。

public static boolean relativeNumber(int input4, int input5){
    for(int i = 1; i <= input4; i++)

显然,这个方法只会返回truefalse,因为main函数只会打印特定的一行,这取决于这两个数字是否互质。
我想我可能需要写两个for循环,分别针对input4input5,可能还需要写一些带有逻辑&&操作数的if语句,但我不确定。

vsmadaxz

vsmadaxz1#

如果它们是互质的,那么最大公约数是1,因为-如果不是这样-两个数字都可以被那个数字整除。所以我们只需要一个算法来计算最大公约数,例如Euclid's method

private static int gcd(int a, int b) {
    int t;
    if(b < a) {
        t = b;
        b = a;
        a = t;
    }
    while(b != 0){
        t = a;
        a = b;
        b = t%b;
    }
    return a;
}

然后:

private static boolean relativelyPrime(int a, int b) {
    return gcd(a,b) == 1;
}
  • 欧几里得算法 * 在 O(log n) 中工作,因此比枚举所有可能的除数快得多,可以优化为 O(sqrt n)
txu3uszq

txu3uszq2#

Swift 4代码用于@williem-van-onsem答案;

func gcd(a: Int, b: Int) -> Int {
    var b = b
    var a = a
    var t: Int!

    while(b != 0){
        t = a;
        a = b;
        b = t%b;
    }
    return a
}

func relativelyPrime(a : Int, b: Int) -> Bool{
    return gcd(a: a, b: b) == 1
}

用途;

print(relativelyPrime(a: 2, b: 4)) // false
vdzxcuhz

vdzxcuhz3#

package stack;

import java.util.Scanner; //To read data from console

/**
*
* @author base
*/
public class Stack {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); // with Scanner we can read data
        int a = in.nextInt(); //first variable
        int b = in.nextInt(); //second variable
        int max; // to store maximum value from a or b
        //Let's find maximum value
        if (a >= b) {
            max = a;
        } else {
            max = b;
        }
        int count = 0; // We count divisible number
        for (int i=2; i<=max; i++) { // we start from 2, because we can't divide on 0, and every number divisible on 1
            if (a % i == 0 && b % i==0) {
                count++; //count them
            }
        }
        if (count == 0) { // if there is no divisible numbers
            System.out.println("Prime"); // that's our solutions
        } else {
            System.out.println("Not Prime"); //otherwise
        }
    }
}

我认为,这是一个简单的解决方案。在评论中提出问题。

相关问题