我正在尝试写一个方法来计算两个数字是否是相对素数的赋值。我主要是在寻找从哪里开始的答案。我知道有一个方法gcd()
可以为我做很多事情,但是赋值几乎让我在没有gcd或数组的情况下做它。
我已经开始了,因为我知道我必须在for循环中使用%
运算符。
public static boolean relativeNumber(int input4, int input5){
for(int i = 1; i <= input4; i++)
显然,这个方法只会返回true
或false
,因为main
函数只会打印特定的一行,这取决于这两个数字是否互质。
我想我可能需要写两个for
循环,分别针对input4
和input5
,可能还需要写一些带有逻辑&&
操作数的if
语句,但我不确定。
3条答案
按热度按时间vsmadaxz1#
如果它们是互质的,那么最大公约数是1,因为-如果不是这样-两个数字都可以被那个数字整除。所以我们只需要一个算法来计算最大公约数,例如Euclid's method:
然后:
txu3uszq2#
Swift 4代码用于@williem-van-onsem答案;
用途;
vdzxcuhz3#
我认为,这是一个简单的解决方案。在评论中提出问题。