Factoring Prime numbers with Java

Factoring Prime numbers with Java

This was an assignment from a cryptography class during my undergrad. This mainly assisted in decrypting a low-bit RSA algorithm but can be used for any purpose.

Essentially it will loop through and perform some mod calculations to figure out the prime factors in the specified range. The three algoritems are used to show that even if a number doesn’t seem to be prime at first, it could be a prime number used in an encryption algorithm.

Feel free to judge… I do not claim to be a Java Dev of any type. (nor want to be…)

[code language=”java”]

/* COSC Algorithm Assignment

*

  • Created By: Bryan

  • Language: Java

  • Compiler: JDK 6.0_65

*

*/

import static java.lang.Math.*; //Calling Math Library

public class COSCAlgorithm { //Main Class

//Declaring Variables

public static int M=3;

public static double X=1;

public static double Y=1;

//Main Function to loop from 3 – 199 iterations

public static void main(String[] args) {

while ( M <= 199) {

algorithmOne(); //Begin Algorithm Sequence, starting with Algorithm 1

M++;

}

} //End Main Function

//Algorithm 1 Function

public static void algorithmOne() {

X = floor(sqrt(M)); //Declaring X for Algorithm 1

if ( pow(X, 2) == M ) {

System.out.println(M + " has a factor of " + X + " — Algorithm 1");

}

else {

X++; //Increase X by 1, then…

algorithmTwo(); //Try Algorithm 2

}

} //End Algorithm 1 Function

//Algorithm 2 Function

public static void algorithmTwo() {

if ( X == (M+1) / 2) {

System.out.println(M + " is a prime — Algorithm 2");

}

else {

Y = sqrt((pow(X,2) – M)); //Declaring Y for Algorithm 2

algorithmThree(); //Try Algorithm 3

}

} //End Algorithm 2 Function

//Algorithm 3 Function

public static void algorithmThree() {

if (pow((floor(Y)), 2) == (pow(X, 2) – M)) {

System.out.println(M + " has factors (X-Y) and (X+Y)");

}

else {

X++; //Increase X by 1, then…

algorithmTwo(); //Try Algorithm 2 again…

}

} //End Algorithm 3 Function

} //End of Class

[/code]

As always please feel free to subscribe/comment/share

Thanks!

-Bryan

Tags// ,
More Reading
Older// Downloads