Last active
May 28, 2016 22:15
-
-
Save dvtate/17e6d45f52c7b9f3d7efcb8888398293 to your computer and use it in GitHub Desktop.
this program factors a semiprime number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <vector>//required of for the primes vector | |
| #include <stdexcept>//out_of_range error handeling | |
| #include <cmath> | |
| /**semi-prime factoring | |
| *Author: Dustin Van Tate Testa | |
| *Purpose: To find the factors of a semi-prime | |
| *Date: spring 2014 | |
| */ | |
| //globals: | |
| //experiment w/ long long ints | |
| unsigned long int sub;//due to limitations, semi-prime must fit the data-type | |
| std::vector<unsigned long int> primes;//holds al the primes | |
| unsigned long int px = 0, py = 0;//primes place finders | |
| bool isp, errcount = 0;//prevents infinite error messages | |
| //functions: | |
| void getprimes();//fill a vector (fancy arr.) of primes less than or equal to sub | |
| void factr(); | |
| int main(){//interface(shit) | |
| std::cout <<"Give me a semi-prime to crack:";//prompt | |
| std::cin >>sub; //get semi-prime | |
| std::cout <<"\nGenerating Primes...\n"; getprimes(); px-=1; | |
| std::cout <<"\nFactoring:\n\n"; | |
| factr(); | |
| std::cout <<"\n"; | |
| } | |
| //process functions | |
| void factr(){//uses recursive process to find factors | |
| py = px--; | |
| isp = 0; | |
| for (unsigned int h = 0; h <= px; h++) | |
| for (unsigned int j = 0; j <= py; j++) | |
| if ((primes.at(j) * primes.at(h)) == sub) {//if j&h are factors of sub | |
| isp = 1; | |
| std::cout <<"-factors: (" <<primes.at(h) <<", " <<primes.at(j) <<")\n";//send answer | |
| } | |
| if (isp == 0) | |
| std::cout <<"The number has no prime factors\n\n"; | |
| } | |
| void getprimes(){//fill a vector of primes less than or equal to sub | |
| unsigned long int i = 0, g; | |
| bool iprm = 1; | |
| while(i <= sub) {//count up for i | |
| g = i - 1; | |
| iprm = 1; | |
| while (iprm && (g > 1)) //test i for primeness | |
| if (i % g-- != 0) | |
| iprm = 0; | |
| if (iprm) { | |
| //add i to the end of the vector (if i is prime) | |
| primes.resize(px); | |
| primes.push_back(i); | |
| //cout <<"(i=" <<i <<")---(primes.at(" <<px <<")="<<primes.at(px) <<")---(size =" <<primes.size() <<")->" <<endl;//used only for testing | |
| px++;//note: must subtract one from final result | |
| } | |
| if (i++ >= 4) | |
| i++;//save resources by incrementing two (evens aren't prime)(errors thrown before 4) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment