I have this recursive function that decompose a number in its prime factors, and show the result standard output for example
descompon(2, 10);
Output
2 = 2
3 = 3
4 = 2^2
5 = 5
6 = 2 * 3
7 = 7
8 = 2^3
9 = 3^2
10 = 2 * 5
The code
#include <iostream>
#include <sstream>
int comprobar_primo( int* num, int e )
{
if (*num%e == 0)
{
*num /= e;
return 1 + comprobar_primo(num, e);
}
return 0;
}
std::string factor_primo(int a, int b, std::stringstream& fact)
{
unsigned exp = comprobar_primo(&a, b);
if (exp >= 1)
{
fact << b;
if (exp > 1) fact << '^' << exp;
if (a != 1) fact << " * ";
}
if (a > 1) factor_primo(a, b + 1, fact);
return fact.str();
}
void descompon(int a, int b, int ver)
{
std::stringstream fact;
//std::string result = factor_primo(a, 2, fact);
if(ver)
std::cout << a << " = " << factor_primo(a, 2, fact) << std::endl;
if(a < b)
descompon( a + 1, b, ver);
}
int main(void)
{
descompon(2, 10000, 1);
return 0;
}
The problem is that when reaches the 5922 the program remains frozen, showing:
Process returned -1073741819 <0xC0000005>
why this happens and how I can avoid?
Both your factor_primo and descompon functions can potentially cause stack overflow. Its better to convert them into iterative version. Modified code is given below:
// no need to pass b as argument since we start from b=2 and increment b by 1
std::string factor_primo(int a, std::stringstream& fact)
{
for(int b=2; a>1; b++)
{
if(a%b==0)
{
unsigned exp=comprobar_primo(&a, b);
if(exp >= 1)
{
fact << b;
if(exp > 1) fact << '^' << exp;
if(a != 1) fact << " * ";
}
}
}
return fact.str();
}
void descompon(int a, int b, int ver)
{
if(ver)
{
for(int i=a; i<=b; i++) {
std::stringstream fact;
std::cout << i << " = " << factor_primo(i, fact) << std::endl;
}
}
}
int main(void)
{
descompon(2, 10000, 1);
getchar();
return 0;
}
Related
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.
I need to sum the members of my progression using recursion. Here's the function which gives my progression and how to count a sum in recursion way?
#include <iostream>
using namespace std;
void progressionRec(int a1, int d, int n) {
if(n <= 1){
cout << a1 << " ";
} else {
int next = a1 + d;
progressionRec(next, d, n - 1);
cout << a1 << " ";
}
}
int main()
{
progressionRec(2,3,15);
return 0;
}
You can sum the members of your progression this way
#include <iostream>
int progressionSum(int a, int d, int n) {
if (n > 0) {
return a + progressionSum(a + d, d, n - 1);
}
return 0;
}
int main()
{
std::cout << "Sum: " << progressionSum(2, 3, 15) << std::endl;
return 0;
}
You may use a functor to store the progress count. Here's an example implementation:
#include <iostream>
using namespace std;
class progressionRec
{
public:
void operator()(int a1, int d, int n) {
++count;
if(n <= 1){
cout << a1 << " ";
} else {
int next = a1 + d;
operator()(next, d, n - 1);
cout << a1 << " ";
}
}
size_t getCount() const
{
return count;
}
private:
std::size_t count = 0;
};
int main()
{
auto func = progressionRec();
func(2,3,15);
std::cout << "\nCount:" << func.getCount() << std::endl;
return 0;
}
Output:
44 41 38 35 32 29 26 23 20 17 14 11 8 5 2
Count:15
You need to change returning type of function to int and return sum on each return:return a1 + progressionRec(next, d, n - 1);
I made a simple recursion program for this question http://www.spoj.com/problems/COINS/, but whenever recursion happens my class variables lose their value and store the value from the recursion loop.
Here's the code:
#include<iostream>
using namespace std;
class a
{
public:
int c = 0, d = 0, b = 0, x = 0;
int recur(int n)
{
b = (n / 2);
if (b >= 12)
{
b = recur(b);
}
c = (n / 3);
if (c >= 12)
{
c = recur(c);
}
d = (n / 4);
if (d >= 12)
{
d = recur(d);
}
x = b + c + d;
return x;
}
};
int main()
{
int n;
while(cin)
{
cin >> n;
int b = 0, r = 0;
a abc;
r = (n > abc.recur(n)) ? (n) : (abc.recur(n));
cout << r << endl;
}
return 0;
}
So for input 12, I'll be getting 13 but for the input value of 44 I'm getting 44.
This could be a working solution:
#include <iostream>
using namespace std;
int changeToDollars(int bytelandians) {
int byTwo = bytelandians / 2;
int byThree = bytelandians / 3;
int byFour = bytelandians / 4;
int sum = byTwo + byThree + byFour;
if (sum < bytelandians) {
return bytelandians;
} else {
return changeToDollars(byTwo) + changeToDollars(byThree) + changeToDollars(byFour);
}
}
int main() {
int bytelandians;
cout << "How much bytelandians?: ";
while (cin >> bytelandians) {
cout << "Corresponding $: " << changeToDollars(bytelandians) << endl;
cout << "How much bytelandians?: ";
}
return 0;
}
The changeToDollars function, using a simple recursive algorithm, exchanges each single Byteland coin into the corresponding three ones with minor value, until the overall converted amount is advantageous.
I wanted to practice math in c++ and I tried making a program that answered this question from math class
0 < r < 1, find the number of rational r values for which the
numerator and the denominator add to make 1000 where r is in simplest
form
After an hour or two debugging, I finally got something that makes it through all the numbers. In class, the answer was 200. I got 216. Run for yourself
#include <math.h>
#include <iostream>
bool rprime_test(int a, int b) {
int tmp = 2;
std::cout << a << "/" << b;
tmp1:
for (tmp; (tmp < a) && (a % tmp != 0); tmp++) {
}
if ((b % tmp == 0 && a % tmp == 0) || b % a == 0) {
std::cout << " == irreduced\n";
return false;
} else if (!tmp < a) {
std::cout << " == reduced\n";
return true;
} else {
//std::cout << tmp << ","<< a << std::endl;
goto tmp1;
}
}
int main() {
int r = 0, a = 1;
int b = 1000 - a;
while (a < b) {
if (rprime_test(a, b)) {
r++;
}
std::cout << "total = " << r << std::endl;
a++;
b = 1000 - a;
//std::cout << "assigned " << a << "/" << b << std::endl;
}
std::cout << "final result = " << r << std::endl;
return 0;
}
please I don't know what I did wrong for this. Also, is there any better way to optimize this?
Your main issue is with your rprime_test function. Without digging too much into your existing function, try using the gcd. Two numbers a and b are an irreducible fraction when they are "coprime," which is when their "greatest common denominator" (gcd) is 1. The way you compute the gcd of two values is with the Euclidean Algorithm:
int gcd (int a, int b) {
return b % a == 0 ? a : gcd (b % a, a);
}
And your check becomes
if (gcd (a, b) == 1) {
a++;
/* etc */
}
Following works:
#include <iostream>
int gcd(unsigned int a, unsigned int b)
{
if (b < a) {
return gcd(b, a);
}
int r = a % b;
while (r != 0) {
a = b;
b = r;
r = a % b;
}
return b;
}
int main()
{
int count = 0;
for (int i = 1; i != 500; ++i) {
if (gcd(1000 - i, i) == 1) {
++count;
}
}
std::cout << count << std::endl;
}
Live example
I am trying to create a program that can take many numbers as I want in C++ language.
Then it find what operators can make the equation true and show all correct possible operation.
Example: If I put 3 5 15
Then it output 3x5 = 15
If I put 1 2 3 4 4
Then it outputs 1+2-3+4 =4
The following code is my written program:
The problem about it is that when I want to reduce the number of input or increase the number of input I need to add/reduce nested loops EVERYTIME. I want to know what is a more effective way of a more flexible nested loops or recursion method.
#include <iostream>
#include <cmath>
using namespace std;
char getOperator(int);
double operate(int, double, double);
int main() {
double a, b, c, d, e, result;
short noOfAnswers = 0;
cout << "Input first 5 numbers to make it equal to another 1 number.\n" <<
"I'll find what are the operators needed to make 2 sides of the equation equal.\n";
cin >> a >> b >> c >> d >> e >> result;
int noOfOperators = 5;
for (int i = 0; i <= noOfOperators; i++) {
double firstTwo = operate(i, a, b);
for (int j = 0; j <= noOfOperators; j++) {
double firstThree = operate(j, firstTwo, c);
for (int k = 0; k <= noOfOperators; k++) {
double firstFour = operate(k, firstThree, d);
for (int l = 0; l <= noOfOperators; l++) {
double firstFive = operate(l, firstFour, e);
if (firstFive == result) {
cout << ++noOfAnswers << ')' << a << getOperator(i) << b << getOperator(j) << c
<< getOperator(k) << d << getOperator(l) << e << '=' << result << endl;
}
}
}
}
}
if (noOfAnswers) cout << "I have found " << noOfAnswers << " solutions for this extremely hard problem for humanity \nin less than a second." << endl;
else cout << "I cannot find any solutions to this problem.\n"
<<"They're just a bunch of random numbers & That is UNSOLVABLE!" << endl;
cout << "Do not doubt my judgment. I am always right!" << endl << "(Please note that all calculations are done from the left side first.)" << endl;
return 0;
}
double operate(int iteration, double num1, double num2) {
switch (iteration) {
case 0: return num1+num2;
case 1: return num1-num2;
case 2: return num1*num2;
case 3: return num1/num2;
case 4: return pow(num1, num2);
case 5: return fmod(num1, num2);
}
return 0;
}
char getOperator(int pos) {
switch (pos) {
case 0: return '+';
case 1: return '-';
case 2: return 'x';
case 3: return '/';
case 4: return '^';
case 5: return '%';
}
return ' ';
}
You might want to use while() loops, cause you dont know when the loop terminates.
int main() {
double numbers[] = {3,5,15};//consider storing the number as an array
//the last element is the result
double result;
int arr_len = sizeof(numbers)/sizeof(double);
int i,j;
while(1)
{
j = 0;
while(j++ < 5)//over all operators
{i = 0;
result = numbers[0];//start with first element
while(i < arrlen - 2)//over all numbers, exclude the result
{
result = operate(j, result, numbers[++i]);
//something like this...this does not work correctly
//it might give you a hint in the right direction
if(result == numbers[arr_len - 1])//compare to last element
return 0;
}
}
}
return 0;
}
Following may help:
// increment v where each value is a digit with maximal value maxSize
// so {0,1,2}, 3 lead to {0,2,0}
// return false on overflow.
bool increment(std::vector<int>& v, int maxSize)
{
for (auto it = v.rbegin(); it != v.rend(); ++it) {
++*it;
if (*it != maxSize) {
return true;
}
*it = 0;
}
return false;
}
// display something like 1 + 2 * 3 = 9 // with the following meaning ((1 + 2) * 3) = 9
void display(const std::vector<double>& operands, const std::vector<int>& operators, double total)
{
const char operators_string[] = "+-*/^%";
std::cout << operands[0];
for (std::size_t i = 0; i != operators.size(); ++i) {
std::cout << " " << operators_string[operators[i]] << " " << operands[i + 1];
}
std::cout << " = " << total << std::endl;
}
// Compute something like {1 2 3 4}, {+ * /} as (((1 + 2) * 3) / 4)
double compute(const std::vector<double>& operands, const std::vector<int>& operators)
{
std::function<double(double, double)> fs[] = {
[](double a, double b) { return a + b; },
[](double a, double b) { return a - b; },
[](double a, double b) { return a * b; },
[](double a, double b) { return a / b; },
[](double a, double b) { return pow(a, b); },
[](double a, double b) { return fmod(a, b); },
};
double res = operands[0];
for (std::size_t i = 0; i != operators.size(); ++i) {
res = fs[operators[i]](res, operands[i + 1]);
}
return res;
}
void display_combinaison(const std::vector<double>& operands, double total)
{
std::vector<int> operators(operands.size() - 1);
do {
if (compute(operands, operators) == total) {
display(operands, operators, total);
}
} while (increment(operators, 6));
}
Live example