I need to print the number of ways you can represent a given number as parts of a prime number.
Let me explain: let's say they gave me this number 7. Now, first of all, I need to find all primes that are less than 7, which are 2, 3, and 5. Now, how much way can I sum these numbers (I can use one number as many times as I want) so that the result is 7? For example, number 7 has five ways:
2 + 2 + 3 2 + 3 + 2 2 + 5 3 + 2 + 2 5 + 2
I completely lost this task. At first, I decided that I was creating an array of elements used: {2, 2, 2, 3, 3, 5} (7/2 = 3, so 2 should appear three times. The same thing happens with 3, which turns out to be two occurrences). After that, scroll through the array and select the βleaderβ, which determines how far we are in the array. I know the explanation is terrible, so here is the code:
#include <iostream> #include <vector> int primes_all[25] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}; int main() { int number; std::cin >> number; std::vector<int> primes_used; for(int i = 0; i < 25; i++) { if(primes_all[i] < number && number-primes_all[i] > 1) { for(int k = 0; k < number/primes_all[i]; k++) primes_used.push_back(primes_all[i]); } else break; } int result = 0; for(size_t i = 0; i < primes_used.size(); i++) { int j = primes_used.size()-1; int new_num = number - primes_used[i]; while(new_num > 1 && j > -1) { if(j > -1) while(primes_used[j] > new_num && j > 0) j--; if(j != i && j > -1) { new_num -= primes_used[j]; std::cout << primes_used[i] << " " << primes_used[j] << " " << new_num << std::endl; } j--; } if(new_num == 0) result++; } std::cout << result << std::endl; system("pause"); return 0; }
It just doesn't work. Just because the idea behind is not so. Here are some border details:
- Time limit: 1 second
- Memory Limit: 128 MB
In addition, the largest number that can be given is 100. That's why I made an array of primes below 100. The result grows very quickly, as this number gets larger, and the BigInteger class will be needed later, but this is not a problem.
Several results are known:
Input Result 7 5 20 732 80 10343662267187
SO ... Any ideas? Is this a combinatorial problem? I don't need code, just an idea. I'm still new to C ++, but I will get along
Keep in mind that 3 + 2 + 2 is different from 2 + 3 + 2. In addition, if this number were prime, it is not taken into account. For example, if the given number is 7, only these amounts are valid:
2 + 2 + 3 2 + 3 + 2 2 + 5 3 + 2 + 2 5 + 2 7 <= excluded