-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
findFactors.cpp
90 lines (79 loc) · 2.12 KB
/
findFactors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Find Factors Cpp
* You put in a number and it prints out the factors
*/
#include <stack>
#include <vector>
#include <string>
#include <iostream>
#include <cmath>
using namespace std;
typedef struct PrimeAndPower {
int prime;
int power;
} PrimeAndPower ;
vector<int> findFactors(int number){
vector<int> factors;
stack<int> other_factors;
double midroot = floor(sqrt(number)) + 1;
for(int guess = 1; guess < midroot; guess++){
if(guess == 1 || number % guess == 0){
factors.push_back(guess);
int other_factor = number / guess;
if(guess != other_factor){
other_factors.push(other_factor);
}
}
}
while(!other_factors.empty()){
factors.push_back(other_factors.top());
other_factors.pop();
}
return factors;
}
vector<PrimeAndPower> primeFactors(int number){
vector<PrimeAndPower> prime_factors;
int workingNumber = number;
for(int guess = 2; guess <= workingNumber; guess ++){
if(workingNumber % guess == 0){
PrimeAndPower primeAndPower;
primeAndPower.prime = guess;
primeAndPower.power = 0;
while( workingNumber > 1 && workingNumber % guess == 0){
workingNumber /= guess;
primeAndPower.power++;
}
prime_factors.push_back(primeAndPower);
}
}
return prime_factors;
}
void usage(string progName){
cout << "USAGE:\n";
cout << "\t" << progName << " <position integer>\n";
cout << "prints out all factors then the prime factorization with primes and powers.\n";
}
int main(int argc, char * argv[]){
if(argc > 1){
cout << "Factors for " << argv[1] << "\n";
int number = stoi(argv[1]);
vector<int> factors = findFactors(number);
for( auto factor : factors ){
cout << factor << " ";
}
cout << "\n";
cout << "Prime Factorization of " << number << "\n";
vector<PrimeAndPower> prime_factors = primeFactors(number);
if(prime_factors.empty()){
cout << number << " is prime.\n";
} else {
for( PrimeAndPower pf : prime_factors ){
cout << pf.prime << "^" << pf.power << " ";
}
}
cout << "\n";
} else {
usage(argv[0]);
}
return 0;
}