Answer the question
In order to leave comments, you need to log in
How to convert a while loop to recursion?
I am a 1st year student. The programming teacher gave an interesting task: to create a calculator for complex numbers (namely, their sum) using Karatsuba's recursive algorithm.
I was able to cope with this task only with the help of cycles. So far, I have little idea how you can use recursion instead of a while loop.
Calculator code below:
#include <math.h>
#include <iostream>
using namespace std;
// подсчет количества разрядов
int getLength(long long value) {
int counter = 0;
while (value != 0) {
counter++;
value /= 10;
}
return counter;
}
long long multiply(long long x, long long y) {
int xLength = getLength(x);
int yLength = getLength(y);
// наибольший из двоих значений
int N = (int)(fmax(xLength, yLength));
// если максимальная длина достаточно маленькая, быстрее просто перемножить два числа обычным методом
if (N < 10)
return x * y;
N = (N / 2) + (N % 2);
// смещение для десятичной системы счисления
long long multiplier = pow(10, N);
long long b = x / multiplier;
long long a = x - (b * multiplier);
long long d = y / multiplier;
long long c = y - (d * multiplier);
long long d0 = multiply(a, c);
long long d1 = multiply(a + b, c + d);
long long d2 = multiply(b, d);
// формула с(t)
return d0 + ((d1 - d0 - d2) * multiplier) + (d2 * (long long)(pow(10, 2 * N)));
}
int main()
{
long long a, b, c, d;
cout << "a: "; cin >> a;
cout << "b: "; cin >> b;
cout << "c: "; cin >> c;
cout << "d: "; cin >> d;
cout << "r = " << (a * c - b * d) << endl;
cout << "s = " << (a * d + b * c) << "i" << endl;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question