当p和q是素数时,找到n = p * q的'p'和'q'

时间:2017-07-18 10:52:37

标签: java rsa brute-force

我得到了这个问题。

n = 77

n = p*q

p and q is a prime number

用蛮力制作p和q的取景器。

到目前为止我的代码:

public class If {

    public static void main(String[] args) {

        int p = 3, q = 3;
        int n = 77;
        int temp = p*q;
        boolean flagp, flagq = false;
        while (temp != n && p <= 77)
        {
            for(int i = 2; i <= p/2; ++i)
            {
                // condition for nonprime number
                if(p % i == 0)
                {
                    flagp = true;
                    break;
                }
                p = p+2;
                q = 3;
                for(int j = 2; j <= q/2; ++j)
                {
                    // condition for nonprime number
                    if(q % j == 0)
                    {
                        flagq = true;
                        break;
                    }
                    q = q+2;
                    temp = p*q;
                }
            }
        }
        System.out.println(temp);
    }
}

我能够找到素数检查。但我似乎无法找到如何循环并找到匹配的pq

4 个答案:

答案 0 :(得分:2)

你不需要p的循环和q的循环。每当您找到n%q == 0的q时,您就可以计算p = n/q。然后,创建一个函数来检查p和q是否都是素数,如果是,则停止循环执行并打印它们。

蛮力编辑:我的坏,蛮力不是我的事,我们的老师把我们关在uni地下室,如果我们用它来解决某些问题,就用链子打我们。因此,在这里使用暴力的方法只是将所有可能的p和q从2乘以n / 2并检查是否p*q == n。没有更多的优化或限制,使它成为一个美丽而缓慢的强力算法。

PD:现在我已经注意到了,也许这实际上并不是蛮力,算法课程让我心烦意乱。感谢上帝,我没有选择欧拉定理。

答案 1 :(得分:2)

import java.math.*;
import java.io.*;
class If {
  public static void main(String[] args) {
    int n=77, p=2, q=0;
    while (n%p>0) { p++; }
    q=77/p;
    System.out.println(new BigInteger(""+q).isProbablePrime(1)?p+" "+q:"No solution exists");
  }
}

编辑:更有用的解决方案

String out="";
String primeFactor(int n) {
  int p=2;
  while (n%p>0 && p<=n){p++;}
  out+=p;
  if (p<n){
    out+=" ";
    primeFactor(n/p);
  }
  return out;
}
System.out.println(primeFactor(77));

答案 2 :(得分:0)

我有一个解决方案(使用BigInteger):

import java.math.BigInteger;

public class If {

    //The first prime number
    public static final BigInteger INIT_NUMBER = new BigInteger("2");

    public static void main(String[] args) {

        //Initialise n and p
        BigInteger n = new BigInteger("77");
        BigInteger p = INIT_NUMBER;

        //For each prime p
        while(p.compareTo(n.divide(INIT_NUMBER)) <= 0){

            //If we find p
            if(n.mod(p).equals(BigInteger.ZERO)){
                //Calculate q
                BigInteger q = n.divide(p);
                //Displays the result
                System.out.println("(" + p + ", " + q + ")");
                //The end of the algorithm
                return;
            }
            //p = the next prime number
            p = p.nextProbablePrime();
        }
        System.out.println("No solution exists");
    }
}

注意:BigInteger类包含许多操作素数的函数。这样可以节省大量时间,并避免与大数字相关的计算错误。

答案 3 :(得分:0)

通用数字域筛选(GNFS)算法是查找素数因子的最有效算法(到目前为止),但编程比上面引用的算法更难。如果你处理的是非常大的数字,你应该使用GNFS。