[英]Calculating a relative Prime of a number in JAVA?
I am working on a program in which I have calculated a number of type long
after applying some calculations according to my algorithm. 我的工作中,我已经计算出了许多类型的程序
long
,根据我的算法应用一些计算之后。 Now, I have to find a relative prime to this number that I have generated. 现在,我必须找到我生成的这个数字的相对素数。 How can I do this?
我怎样才能做到这一点? I know that if two numbers are relative prime then their
GCD == 1
but in this case I don't have another number. 我知道如果两个数字是相对质数,那么它们的
GCD == 1
但在这种情况下我没有另一个数字。 I have only one number which is getting generated in my program and I need to calculate a relative prime number for this number. 我只有一个数字在我的程序中生成,我需要计算这个数字的相对素数。
Edit 编辑
Condition for generating relative prime is such that: 生成相对素数的条件是这样的:
1 < relative prime < generated Number
Any help is appreciated. 任何帮助表示赞赏。
Now, I have to find a relative prime to this number
现在,我必须找到这个数字的相对素数
For whole number n
where n>2
it is always true that n
and n-1
are relatively prime. 对于整数
n
,其中n>2
, n
和n-1
总是相对素数。 So assuming n
isn't 2 or less, simply have n-1
be the output, as it is guaranteed relatively prime. 所以假设
n
不是2或更小,只需要输出n-1
,因为它保证相对素数。 If n
equals 2 then your condition is impossible. 如果
n
等于2,那么你的条件是不可能的。
You can always actually calculate GCDs if you want a non-trivial solution. 如果你想要一个非平凡的解决方案,你总是可以实际计算GCD。 Use Euclid's method as follows:
使用Euclid的方法如下:
long findGCD(long l1, long l2) {
//end recursion
if(l2 == 0){
return number1;
}
return findGCD(l2, l1%l2);
}
and use a while loop to try all numbers starting at n+2
until you get a GCD of 1. 并使用while循环尝试从
n+2
开始的所有数字,直到得到GCD为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.