How to find out if two numbers are relatively prime?

混江龙づ霸主 提交于 2019-12-05 01:10:44

Well in case they are relatively prime, the greatest common divider is one, because - if otherwise - both numbers could be devided by that number. So we only need an algorithm to calculate the greatest common divider, for instance Euclid's method:

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

And then:

private static boolean relativelyPrime(int a, int b) {
    return gcd(a,b) == 1;
}

Euclid's algorithm works in O(log n) which thus is way faster than enumerating over all potential divisors which can be optimized to O(sqrt n).

Swift 4 code for @williem-van-onsem answer;

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
}

Usage;

print(relativelyPrime(a: 2, b: 4)) // false
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
        }
    }
}

I think that, this is the simple solution. Ask questions in comments.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!