I am writing a parallel prime factorization program in C++. I managed to get all of the threading and finding out the prime pretty well but its the very end that I can't seem to get. When the user enters more than one number to find the prime factor of, it prints the entire array of prime factorization. I want it to only print the prime factors related to a unique number.
I would like to change it to where the line after "The prime factorization of 10 is" doesn't print the entire vector of prime numbers. All of the printing occurs towards the bottom of the main function. To be very specific, if I were to type in two 10's, the output should be:
---desired output---
"The prime factorization of 10 is"
"2 5"
"The prime factorization of 10 is"
"2 5"
---/desired output---
do not worry about the "there are: 0 prime numbers" part. I know how to fix that already
Any and all help is appreciated!
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <mutex>
#include <list>
#include <algorithm>
using namespace std;
using namespace std::chrono;
int userInput; // This number is used to help store the user input
vector<long long> vec(0); // A vector storing all of the information
int numPrimes; // Used to count how many prime numbers there are
bool PRINT = false; // lets me decide if I want to print everything for debugging purposes
int arraySize;
vector<thread> threads;
vector<vector<long long> > ending;
void getUserInput()
{
//while the user has not entered 0, collect the numbers.
cout << "Please enter a number for prime factorization. Enter 0 to quit" << endl;
do
{
cin >> userInput;
if (userInput != 0)
{
vec.push_back(userInput);
arraySize++;
}
} while (userInput != 0);
}
vector<long long> primeFactors(long long n)
{
vector<long long> temp;
while (n % 2 == 0)
{
temp.push_back(n);
numPrimes++;
n = n / 2;
}
for (int i = 3; i <= sqrt(n); i = i + 2)
{
while (n%i == 0)
{
temp.push_back(n);
numPrimes++;
n = n / i;
}
}
if (n > 2)
{
temp.push_back(n);
numPrimes++;
}
return temp;
}
void format()
{
cout << endl;
}
bool isPrime(long long number){
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; (i*i) <= number; i += 2){
if (number % i == 0) return false;
}
return true;
}
vector<long long> GetPrimeFactors(long long num)
{
vector<long long> v;
for (int i = 2; i <= num; i++)
{
while (num % i == 0)
{
num /= i;
v.push_back(i);
}
}
return v;
}
int main()
{
// how to find out how many cores are available.
getUserInput();
high_resolution_clock::time_point t1 = high_resolution_clock::now();
// vector container stores threads
format();
for (int i = 0; i < arraySize; ++i)
{
vector<long long> temp;
threads.push_back(thread([&]
{
ending.push_back(GetPrimeFactors(vec.at(i)));
}));
}
// allow all of the threads to join
for (auto& th : threads)
{
th.join();
}
for (int i = 0; i < arraySize; ++i)
{
cout << "The prime factorization of " << vec.at(i) << " is \n" << endl;
for (int m = 0; m < ending.size(); m++)
{
vector<long long> v = ending[m];
for (int k = 0; k < v.size(); k++)
{
cout << v.at(k) << " ";
}
}
cout << endl;
}
format();
cout << "There are: " << numPrimes << " prime numbers" << endl;
//time
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(t2 - t1).count();
format();
cout << "Time in seconds: " << (duration / 1000000.0) << endl;
format();
}
This was too long for a comment so, I'm posting this as an answer
You could also try this
#include <iostream>
using namespace std;
long long Number;
int Prime[10000];
void Gen()
{
Prime[0]=2;
Prime[1]=3;
bool IsPrime;
long long Counter=2;
for( int ii=4 ; Counter<10000 ; ii++ )
{
IsPrime=true;
for( int jj=0 ; Prime[jj]<=sqrt(ii) ; jj++ )
{
if(ii%Prime[jj]==0)
{
IsPrime=false;
break;
}
}
if(IsPrime)
{
Prime[Counter]=ii;
Counter++;
}
}
}
int main()
{
int Factor[10000]={0};
Gen();
cout<<"Enter Number"<<endl;
cin>>Number;
Factorize :
for( int ii=0 ; ii<10000 ; ii++ )
{
if(Number<Prime[ii])
{
break;
}
if(Number%Prime[ii]==0)
{
Number/=Prime[ii];
Factor[ii]=1;
if(Number==1)
{
break;
}
goto Factorize;
}
}
for( int ii=0 ; ii<10000 ; ii++ )
{
if(Factor[ii])
{
cout<<Prime[ii]<<" ";
}
}
}
Well, what I'm doing is I'm first generating array of primes, then I'm dividing given Number from elements of Prime array. If Number is divisible by respective prime factor then I'm marking it's index in factor array as a factor, Then I'm iterating over factor array, if any element is marked as factor then I'm printing it.
Actually, You can adjust number of elements in array as per your requirements.
So I figured it out:
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
using namespace std;
using namespace std::chrono;
int userInput; // This number is used to help store the user input
vector<long long> vec(0); // A vector storing all of the information
int numPrimes; // Used to count how many prime numbers there are
int arraySize;
vector<thread> threads;
vector<vector<long long> > ending;
void getUserInput()
{
//while the user has not entered 0, collect the numbers.
cout << "Please enter a number for prime factorization. Enter 0 to quit" << endl;
do
{
cin >> userInput;
if (userInput != 0)
{
vec.push_back(userInput);
arraySize++;
}
} while (userInput != 0);
}
void format()
{
cout << endl;
}
bool isPrime(long long number){
if (number < 2) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; (i*i) <= number; i += 2){
if (number % i == 0) return false;
}
return true;
}
vector<long long> GetPrimeFactors(long long num)
{
vector<long long> v;
for (int i = 2; i <= num; i++)
{
while (num % i == 0)
{
num /= i;
v.push_back(i);
numPrimes++;
}
}
return v;
}
int main()
{
// how to find out how many cores are available.
getUserInput();
high_resolution_clock::time_point t1 = high_resolution_clock::now();
// vector container stores threads
format();
for (int i = 0; i < arraySize; ++i)
{
vector<long long> temp;
threads.push_back(thread([&]
{
ending.push_back(GetPrimeFactors(vec.at(i)));
}));
}
// allow all of the threads to join
for (auto& th : threads)
{
th.join();
}
for (int i = 0; i < arraySize; ++i)
{
cout << "The prime factorization of " << vec.at(i) << " is \n" << endl;
vector<long long> temp = ending[i];
for (int m = 0; m < temp.size(); m++)
{
cout << temp.at(m) << " ";
}
cout << endl;
}
format();
cout << "There are: " << numPrimes << " prime numbers" << endl;
//time
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(t2 - t1).count();
format();
cout << "Time in seconds: " << (duration / 1000000.0) << endl;
format();
}
Related
Write a function int fact(int n) which displays the factors of the integer n, and returns the number of factors. Call this function in main() with user input
#include<iostream>
using namespace std;
int fact(int n);
int main() {
int n,factor;
cout << "Enter an integer : ";
cin >> n;
factor = fact(n);
cout << factor;
return 0;
}
int fact(int n)
{
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
cout << i << endl;
}
return 0;
}
If I enter 7, I get 1,7,0 . How do i remove this 0 and how do i find the number of factors?
You should count in your int fact() function. Set a variable to 0 and increment each time you currently display i. Then at the end of the function instead of returning 0 return the count variable.
int fact(int n)
{
int count=0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
count++;
}
}
return count;
}
The key part is "and returns the number of factors". You don't do that. Keep a count of the factors:
int fact(int n)
{
int count = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
{
// found a factor, add to the count
count++;
cout << i << endl;
}
}
// return the count instead
return count;
}
Then, your main function can use that count:
factor = fact(n); // fact(n) will already print the factors
// now just print the number
cout << "Number of factors: " << factor << '\n';
#include <iostream>
#include <vector>
std::vector<int> fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
std::vector<int> factors = fact(n);
for (auto i : factors) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "Number of factors: " << factors.size() << '\n';
return 0;
}
std::vector<int> fact(int n) {
std::vector<int> vec{1};
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
vec.push_back(i);
}
}
vec.push_back(n);
return vec;
}
If you're going to return anything from fact(), it should be the factors. To do so, I am using a std::vector. It is an array that can grow on demand. The numbers 1 and n are always factors, so I don't bother doing the math for them. The vector is initialized already holding the value 1, and I only calculate numbers up to and including half of n (Anything greater than n/2 won't divide evenly, so my loop is finished about half as fast by recognizing the actual range). I then just add n to the vector, which I return.
My main prints the vector, and the vector knows its own size, which is the number of factors.
Alternatively, you can just keep a count in your fact() function.
#include <iostream>
#include <vector>
// Prints factors of n and returns the number of factors
int fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
int numFactors = fact(n);
std::cout << "Number of factors: " << numFactors << '\n';
return 0;
}
int fact(int n) {
int factorCount = 2; // Already counting 1 and n
std::cout << "1 ";
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
std::cout << i << ' ';
++factorCount;
}
}
std::cout << n << '\n';
return factorCount;
}
The main problem with your code is that your function always returns zero. You need to keep a count of factors and return it.
Besides that your code performance badly as the loop goes on much longer than needed. You can use the square root of n as the limit in the for loop. Like:
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int limit = sqrt(n);
for (int i = 1; i <= limit; ++i)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
}
if (limit * limit == n)
{
--res;
}
return res;
}
For n = 36 the output is:
1 - 36
2 - 18
3 - 12
4 - 9
6 - 6
and the returned value is 9
Below is another approach. It doesn't use square root. Instead it keeps the number of loops low by using the square of i as loop limit.
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int i = 1;
int i_square = i * i;
while (i_square < n)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
++i;
i_square = i * i;
}
if (i_square == n)
{
++res;
cout << i << " - " << n/i << endl;
}
return res;
}
Fact() always returns 0 so this line print 0
cout << factor;
for the number of factors you can change the return value of fact() :
int fact(int n)
{
int nb = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
nb++;
}
}
return nb;
}
So far I have this code. I'm trying to print prime factorization with exponents. For example, if my input is 20, the output should be 2^2, 5
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors (int n);
bool prime( int n);
int main(int argc, char** argv) {
int n = 0 ;
cout << "Enter a number and press Enter: ";
cin >>n;
cout << " Number n is " << n << endl;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n){
double sqrt_of_n = sqrt(n);
for (int i =2; i <= sqrt_of_n; ++i){
if (prime (i)){
if (n % i == 0){
cout << i << ", ";
get_divisors(n / i);
return;
}
}
}
cout << n;
}
bool prime (int n){
double sqrt_of_n = sqrt (n);
for (int i = 2; i <= sqrt_of_n; ++i){
if ( n % i == 0) return 0;
}
return 1;
}
I hope someone can help me with this.
You can use an std::unordered_map<int, int> to store two numbers (x and n for x^n). Basically, factorize the number normally by looping through prime numbers smaller than the number itself, dividing the number by the each prime as many times as possible, and recording each prime you divide by. Each time you divide by a prime number p, increment the counter at map[p].
I've put together a sample implementation, from some old code I had. It asks for a number and factorizes it, displaying everything in x^n.
#include <iostream>
#include <unordered_map>
#include <cmath>
bool isPrime(const int& x) {
if (x < 3 || x % 2 == 0) {
return x == 2;
} else {
for (int i = 3; i < (int) (std::pow(x, 0.5) + 2); i += 2) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
std::unordered_map<int, int> prime_factorize(const int &x) {
int currentX = abs(x);
if (isPrime(currentX) || currentX < 4) {
return {{currentX, 1}};
}
std::unordered_map<int, int> primeFactors = {};
while (currentX % 2 == 0) {
if (primeFactors.find(2) != primeFactors.end()) {
primeFactors[2]++;
} else {
primeFactors[2] = 1;
}
currentX /= 2;
}
for (int i = 3; i <= currentX; i += 2) {
if (isPrime(i)) {
while (currentX % i == 0) {
if (primeFactors.find(i) != primeFactors.end()) {
primeFactors[i]++;
} else {
primeFactors[i] = 1;
}
currentX /= i;
}
}
}
return primeFactors;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
auto factors = prime_factorize(x);
std::cout << x << " = ";
for (auto p : factors) {
std::cout << "(" << p.first << " ^ " << p.second << ")";
}
}
Sample output:
Enter a number: 1238
1238 = (619 ^ 1)(2 ^ 1)
To begin with, avoid using namespace std at the top of your program. Second, don't use function declarations when you can put your definitions before the use of those functions (but this may be a matter of preference).
When finding primes, I'd divide the number by 2, then by 3, and so on. I can also try with 4, but I'll never be able to divide by 4 if 2 was a divisor, so non primes are automatically skipped.
This is a possible solution:
#include <iostream>
int main(void)
{
int n = 3 * 5 * 5 * 262417;
bool first = true;
int i = 2;
int count = 0;
while (i > 1) {
if (n % i == 0) {
n /= i;
++count;
}
else {
if (count > 0) {
if (!first)
std::cout << ", ";
std::cout << i;
if (count > 1)
std::cout << "^" << count;
first = false;
count = 0;
}
i++;
if (i * i > n)
i = n;
}
}
std::cout << "\n";
return 0;
}
Note the i * i > n which is an alternative to the sqrt() you are using.
How do I correctly dereference pointers to arrays of long.
In the function main my code seems to print the addresses instead of the long values.
#include <list>
#include <iostream>
#include <cmath>
#include <vector>
bool
is_prime (long i)
{
// fix wrong return values for 0 and 1
if (i <= 1)
return false;
const long j = (long) std::sqrt(i);
for (long k=2; k<j+1; ++k) {
if (i % k == 0)
return false;
}
return true;
}
std::list<long(*)[2]>
goldbach (long number)
{
std::list<long(*)[2]> sums;
std::list<long(*)[2]>::iterator it;
if (number < 4) // Exclude too small integers.
return sums;
if (number % 2) // Exclude uneven numbers.
return sums;
it = sums.begin();
for (long candidate=2; candidate < number; ++candidate)
{
if (is_prime(candidate))
{
if (is_prime(number - candidate))
{
long sum[2];
sum[0] = candidate;
sum[1] = number - candidate;
std::cout << sum[0] << " + " << sum[1] << "\n";
sums.insert(it, &sum);
++it;
}
}
}
return sums;
}
int
main ()
{
std::list<long(*)[2]> sums;
std::list<long(*)[2]>::iterator it;
for(long i = 4; i < 100; i+=2)
{
std::cout << "### " << i << " ###" << "\n";
sums = goldbach(i);
for (it = sums.begin(); it != sums.end(); ++it)
{
long num1 = *((*it)[0]);
long num2 = *((*it)[1]);
std::cout << num1 << " + " << num2 << "\n";
}
std::cout << "\n\n";
}
}
Thanks to the comments I realized that arrays within lists are a bad idea in C++.
I changed my code to the following, which works:
#include <list>
#include <iostream>
#include <cmath>
#include <vector>
bool
is_prime (long i)
{
// fix wrong return values for 0 and 1
if (i <= 1)
return false;
const long j = (long) std::sqrt(i);
for (long k=2; k<j+1; ++k) {
if (i % k == 0)
return false;
}
return true;
}
std::list<std::pair<long, long>>
goldbach (long number)
{
std::list<std::pair<long, long>> sums;
std::list<std::pair<long, long>>::iterator it;
if (number < 4) // Exclude too small integers.
return sums;
if (number % 2) // Exclude uneven numbers.
return sums;
it = sums.begin();
long complement;
for (long candidate=2; candidate < number; ++candidate)
{
if (is_prime(candidate))
{
complement = number - candidate;
if (is_prime(complement))
{
std::pair<long, long> sum = std::make_pair(candidate, complement);
sums.insert(it, sum);
++it;
}
}
}
return sums;
}
int
main ()
{
std::list<std::pair<long, long>> sums;
std::list<std::pair<long, long>>::iterator it;
for(long i = 4; i < 100; i+=2)
{
std::cout << "### " << i << " ###" << "\n";
sums = goldbach(i);
for (it = sums.begin(); it != sums.end(); ++it)
{
std::cout << it->first << " + " << it->second << "\n";
}
std::cout << "\n\n";
}
}
how i could run fast dynamic programming algorithm to get all the possible answers .
imagine we have 20 entries and it only shows 1 line of best answers , i want it to run all the way and show the others too, till all the entries are shows as a result, and no repetitions is allowed .
thank you so much. really appreciate it.
here is the code :
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <utility>
using namespace std;
float W ,N; //N = olcu sayisi, W = profil boyu
vector<float> numbers; //stores the set of numbers
pair<float, multiset<float>> calc(float i, float j) //returns closest sum and best subset of the first i numbers for the target value j
{
static map<pair<float, float>, pair<float, multiset<float>>> dp; //stores results to avoid repeated calculations
pair<float, float> p(i, j); //pair for convenience
if(i == 0) //base case
{
return make_pair(0, multiset<float>(
{}));
}
auto findResult = dp.find(p);
if(findResult != dp.end()) //check if already calculated
{
return findResult->second;
}
auto temp1 = calc(i - 1, j); //compute result if not using number
if(numbers[i - 1] > j) //if current number is too big
{
return temp1;
}
auto temp2 = calc(i - 1, j - numbers[i - 1]); //compute result if using number
temp2.first += numbers[i - 1];
temp2.second.insert(numbers[i - 1]);
pair<float, multiset<float>> result;
if(temp1.first != temp2.first) //compare results and choose best
{
result = temp1.first > temp2.first ? temp1 : temp2;
}
else
{
result = temp1.second.size() < temp2.second.size() ? temp1 : temp2;
}
dp[p] = result;
return result;
}
int main()
{
cout << "sineklik sayisi: ";
cin >> N;
N = 2 * N;
cout << "Profil olcusu: ";
cin >> W;
numbers.reserve(N); //avoid extra reallocations
cout << "Olculeri giriniz: ";
for(int i = 0; i < N; i++) //input loop
{
float temp;
cin >> temp;
numbers.push_back(temp);
}
pair<float, multiset<float>> result = calc(N, W); //calculate
//output below
cout << "The best possible sum is " << result.first << " Left behind is " << W - result.first << ", obtained using the set of numbers {";
if(result.second.size() > 0)
{
cout << *result.second.begin();
for(auto i = ++result.second.begin(); i != result.second.end(); i++)
{
cout << ", " << *i;
}
}
cout << "}.\n";
}
Edit: This is one of my older answers. I wasn't as good back then, and now I know there is a much simpler, faster, and less memory-consuming solution to this problem. If we compute the DP bottom-up in a table that only stores the closest possible sum, we can reconstruct the subsets recursively later using the table values we computed.
A solution that outputs all sets of numbers with sum equal to the greatest possible sum not greater than the target value and containing the least possible number of numbers:
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <utility>
using namespace std;
int N, W; //N = number of numbers, W = target sum
vector<int> numbers; //stores the set of numbers
pair<int, set<multiset<int>>> calc(int i, int j) //returns closest sum and best subset of the first i numbers for the target value j
{
static map<pair<int, int>, pair<int, set<multiset<int>>>> dp; //stores results to avoid repeated calculations
pair<int, int> p(i, j); //pair for convenience
if(i == 0) //base case
{
set<multiset<int>> temp;
temp.emplace();
return make_pair(0, temp);
}
auto findResult = dp.find(p);
if(findResult != dp.end()) //check if already calculated
{
return findResult->second;
}
auto temp1 = calc(i - 1, j); //compute result if not using number
if(numbers[i - 1] > j) //if current number is too big
{
return temp1;
}
pair<int, set<multiset<int>>> temp2 = calc(i - 1, j - numbers[i - 1]), newtemp2; //compute result if using number
newtemp2.first = temp2.first + numbers[i - 1];
for(const auto k : temp2.second)
{
multiset<int> temp = k;
temp.insert(numbers[i - 1]);
newtemp2.second.insert(temp);
}
pair<int, set<multiset<int>>> *result;
if(temp1.first != newtemp2.first) //compare results and choose best
{
result = temp1.first > newtemp2.first ? &temp1 : &newtemp2;
}
else if(temp1.second.begin()->size() != newtemp2.second.begin()->size())
{
result =
temp1.second.begin()->size() < newtemp2.second.begin()->size() ? &temp1 : &newtemp2;
}
else
{
temp1.second.insert(newtemp2.second.begin(), newtemp2.second.end());
result = &temp1;
}
dp.insert(make_pair(p, *result));
return *result;
}
int main()
{
cout << "Enter the number of numbers: ";
cin >> N;
cout << "Enter target sum: ";
cin >> W;
numbers.reserve(N); //avoid extra reallocations
cout << "Enter the numbers: ";
for(int i = 0; i < N; i++) //input loop
{
int temp;
cin >> temp;
numbers.push_back(temp);
}
pair<int, set<multiset<int>>> result = calc(N, W); //calculate
//output below
cout << "The best possible sum is " << result.first << ", which can be obtained using a set of "
<< result.second.begin()->size() << " numbers " << result.second.size()
<< " different ways:\n";
for(const auto &i : result.second)
{
cout << '{';
if(i.size() > 0)
{
cout << *i.begin();
for(auto j = ++i.begin(); j != i.end(); ++j)
{
cout << ", " << *j;
}
}
cout << "}\n";
}
}
This solution will not allow a number to appear in the output more than the number of times it appeared in the input. If you want to only allow a number to appear once in the output even if it appeared multiple times in the input, change the multiset numbersleft to a set.
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <utility>
using namespace std;
int N, W; //N = number of numbers, W = target sum
vector<int> numbers; //stores the set of numbers
pair<int, set<multiset<int>>> calc(int i, int j) //returns closest sum and best subset of the first i numbers for the target value j
{
static map<pair<int, int>, pair<int, set<multiset<int>>>> dp; //stores results to avoid repeated calculations
pair<int, int> p(i, j); //pair for convenience
if(i == 0) //base case
{
set<multiset<int>> temp;
temp.emplace();
return make_pair(0, temp);
}
auto findResult = dp.find(p);
if(findResult != dp.end()) //check if already calculated
{
return findResult->second;
}
auto temp1 = calc(i - 1, j); //compute result if not using number
if(numbers[i - 1] > j) //if current number is too big
{
return temp1;
}
pair<int, set<multiset<int>>> temp2 = calc(i - 1, j - numbers[i - 1]), newtemp2; //compute result if using number
newtemp2.first = temp2.first + numbers[i - 1];
for(const auto k : temp2.second)
{
multiset<int> temp = k;
temp.insert(numbers[i - 1]);
newtemp2.second.insert(temp);
}
pair<int, set<multiset<int>>> *result;
if(temp1.first != newtemp2.first) //compare results and choose best
{
result = temp1.first > newtemp2.first ? &temp1 : &newtemp2;
}
else if(temp1.second.begin()->size() != newtemp2.second.begin()->size())
{
result =
temp1.second.begin()->size() < newtemp2.second.begin()->size() ? &temp1 : &newtemp2;
}
else
{
temp1.second.insert(newtemp2.second.begin(), newtemp2.second.end());
result = &temp1;
}
dp.insert(make_pair(p, *result));
return *result;
}
int main()
{
cout << "Enter the number of numbers: ";
cin >> N;
cout << "Enter target sum: ";
cin >> W;
numbers.reserve(N); //avoid extra reallocations
cout << "Enter the numbers: ";
for(int i = 0; i < N; i++) //input loop
{
int temp;
cin >> temp;
numbers.push_back(temp);
}
pair<int, set<multiset<int>>> result = calc(N, W); //calculate
//output below
cout << "The best possible sum is " << result.first << ", which can be obtained using sets of "
<< result.second.begin()->size() << " numbers:\n";
multiset<int> numbersleft;
numbersleft.insert(numbers.begin(), numbers.end());
for(const auto &i : result.second)
{
bool good = true;
for(const int &j : i)
{
if(numbersleft.find(j) == numbersleft.end())
{
good = false;
break;
}
}
if(good)
{
for(const int &j : i)
{
numbersleft.erase(j);
}
cout << '{';
if(i.size() > 0)
{
cout << *i.begin();
for(auto j = ++i.begin(); j != i.end(); ++j)
{
cout << ", " << *j;
}
}
cout << "}\n";
}
}
}
I'm trying to write a function that would return a prime factorisation of a given number (as part of solving project euler's problem #12). To count the prime factors. I use std::map.
The code is as follows:
#include "stdafx.h"
#include <iostream>
#include <map>
#include <algorithm>
bool IsPrime(unsigned int number)
{
if (number < 1) return 0; // zero is not prime. For our purposes, one would be.
for (unsigned int i = 2; i*i <= number; ++i)
{
if (number % i == 0)
return false;
}
return true;
}
int divisors(unsigned int num)
{
int orig_num = num;
std::map <int, int> primefactors;
for(unsigned int i = 1; i <= num; ++i)
if (num % i == 0 && IsPrime(i))
{
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
std::cout << orig_num << " = ";
for(auto& iter:primefactors)
std::cout << iter.first << "^" << iter.second << " * ";
return 0;
}
int main()
{
divisors(661500);
return 0;
}
The problem is that all the counts of primefactors are returned as 1s, although the number in main was chosen specifically to be a product of primes to larger than 1 powers (661500 = 1^1*2^2*3^3*5^3*7^2).
My guess is that I'm incrementing something wrong.
You are dividing only once per prime. But you should continue dividing by the prime as long as number is divisible by it:
for(unsigned int i = 2; i <= num; ++i)
if (IsPrime(i))
{
while (num % i == 0) {
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
}
Actually there is no need for IsPrime(i) condition:
for(unsigned int i = 2; i <= num; ++i)
while (num % i == 0) {
num /= i;
++primefactors[i];
std::cout << primefactors[i] << "\t";
}
Proof: if i is not a prime, then condition num % i == 0 implies that num is divisible by a prime factor p of i. But p < i so our loop had to go through p some time before i. And while loop would effectively erase all occurences of p in num. In particular by the time that for reaches i we have that num is no longer divisible by p. Contradiction. I.e. in the loop above if num % i == 0 is satisfied, then i is prime.