Recursively storing integers in an array - c++

I have problem with recursive functions.
I have to build a recursive function which creates an array of integer values corresponding to the digits of a given number.
For example, if I input a number like 3562, it should look like :
myArray[0] = 3
myArray[1] = 5
myArray[2] = 6
myArray[3] = 2
Here is my code :
#include <iostream>
using namespace std;
int myFunction(int num, int lenOfNum);
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
cout << myFunction(number, lengthCount) << endl;
}
int myFunction(int num, int lenOfNum){
int arr[lenOfNum];
if(num > 0){
for(int i = 0; i < lenOfNum; i++){
arr[i] = num/=10;
cout << "arr[" << i + 1 << " ]= " << arr[i] << endl;
}
return myFunction(num, lenOfNum);
}
else if(num == 0){
return 0;
} else;
}

The problem with your code is that you are calling int arr[lenOfNum] in each method call, which in short creates an array with a new reference to a memory location that can store lenOfNum integers.
To solve this, we declare the array in the main method and pass it as a parameter to the function.
int main() {
// somewhere in main after reading lenOfNum
int arr[lenOfNum];
// somewhere in main after declaring an array
myFunction(arr, number, lengthCount - 1);
}
and myFunction as
void myFunction(int *arr, int num, int idx) {
if (idx < 0) return; // you've completed processing the num
else if (num == 0) {
arr[0] = 0;
return;
}
arr[idx--] = num % 10;
myFunction(arr, num / 10, idx);
}

Using vector and rest part of your example
#include <iostream>
using namespace std;
void myFunction(vector<int> &arr, int num, int lenOfNum){
if (num < 0) {
return;
}
else if (num == 0) {
return;
}
int next_idx = lenOfNum - 1;
int digit = num % 10;
arr[next_idx] = digit;
myFunction(arr, num / 10, next_idx);
}
int main(){
int number;
int lengthCount = 0;
cout <<"Input numbers" << endl;
cin >> number;
int temp = number;
for(; number != 0; number /= 10, lengthCount++);
number = temp;
auto arr = vector<int>(lengthCount, 0);
myFunction(arr, number, lengthCount);
for(int i = 0; i < arr.size(); i++){
cout << "arr[" << i << " ]= " << arr[i] << endl;
}
}

Works for positive numbers
#include <vector>
#include <stdio.h>
std::vector<int> myFunction(int num)
{
std::vector<int> ret;
int irec = num / 10;
if (irec > 0)
ret = myFunction(irec);
ret.push_back('0' + (num % 10));
return ret;
}
int main(int argc, char *argv[])
{
std::vector<int> res = myFunction(539);
for(unsigned int i = 0; i < res.size(); i++)
printf("%c,", res[i]);
}

Related

I am trying to add large numbers using arrays without using bigint or anything like that. C++

I am trying to add large numbers using arrays without using bigint or anything like that. I can get my program to add the two arrays. However, I need to take the addition of the arrays and output the correct answer like a regular number. I cannot seem to make an algorithm to take the sum of my arrays and ouptut the answer. Does anybody have any tips or suggestions?
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
const int DIGITS = 20;
void readNum(int list[], int& length, string input1);
void reverseArray(int arr[], int start, int end);
void sumNum(int list1[], int numOfElementsList1,
int list2[], int numOfElementsList2);
int main()
{
// Write your main here
string input1;
string input2;
int list[DIGITS];
int list2[DIGITS];
int total[DIGITS];
int input1Length;
int input2Length;
cout << "Please enter your 1st number: " << endl;
cin >> input1;
cout << "Please enter your 2nd number: " << endl;
cin >> input2;
input1Length = input1.length();
input2Length = input2.length();
readNum(list, input1Length, input1);
readNum(list2, input2Length, input2);
reverseArray(list, 0, input1Length);
reverseArray(list2, 0, input2Length);
sumNum(list, input1Length, list2, input2Length);
}
void readNum(int list[], int& length, string input1)
{
int array[DIGITS];
for (int i = 0; i < length; i++)
{
array[i] = input1[i] - '0';
list[i] = array[i];
}
}
void reverseArray(int arr[], int start, int length)
{
int end;
end = length - 1;
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void sumNum(int list1[], int numOfElementsList1,
int list2[], int numOfElementsList2)
{
int length;
int sum = 0;
int carry = 0;
int total[DIGITS];
if (numOfElementsList1 > numOfElementsList2)
{
length = numOfElementsList1;
}
else
{
length = numOfElementsList2;
}
for (int i = 0; i < length; i++)
{
sum = list1[i] + list2[i] + carry;
if (sum >= 10)
{
sum = sum % 10;
carry = 1;
}
else
{
carry = 0;
}
total[i] = sum;
cout << total[i];
}
}
Strings are arrays of characters, you could just use them as-is. The advantage being... they're just strings, and you can output them as a string just as easily. Not a new technique, it's called a binary coded decimal which in this case is a zoned BCD (where the zone is 0x30 in ASCII, or zone 0xF0 in EBCDIC).
#include <iostream>
#include <string>
#include <stdexcept>
using std::string;
using std::cout;
using std::cin;
using std::runtime_error;
static string sumNum(string, string);
int main() {
string input1;
string input2;
cout << "Please enter your 1st number: ";
cin >> input1;
cout << "Please enter your 2nd number: ";
cin >> input2;
auto sum = sumNum(input1, input2);
cout << "Sum is: " << sum << "\n";
}
string sumNum(string a, string b) {
//a = string(a.rbegin(), a.rend());
//b = string(b.rbegin(), b.rend());
string sum;
auto digit = [carry = 0](int value) mutable {
value += carry;
if (value > 9) {
carry = 1;
value -= 10;
} else {
carry = 0;
}
return static_cast<char>(value + '0');
};
auto num = [](char c) {
if (c < '0' || c > '9') {
throw runtime_error("not a digit");
}
return c - '0';
};
auto aa = a.rbegin();
auto bb = b.rbegin();
while(aa != a.rend() && bb != b.rend()) {
sum.push_back(digit((num(*aa)) + (num(*bb))));
++aa;
++bb;
}
while (aa != a.rend()) {
sum.push_back(digit(num(*aa)));
++aa;
}
while (bb != b.rend()) {
sum.push_back(digit(num(*bb)));
++bb;
}
char last = digit(0);
if (last != '0')
sum.push_back(last);
return string(sum.rbegin(), sum.rend());
}

C++) how to distinct 1.0E+1000 number's aliquot?

If input A < 10^1000 , b = common int <100000
how can Ii know that A is multiple of B or not?
int main()
{
int testcase = 0;
cin >> testcase;
for (int i = 0; i < testcase; i++)
{
long long num;
int div = 0;
cin >> num >> div;
if (num % div == 0)
{
cout << 1 << endl;
}
else
{
cout << 0 << endl;
}
}
return 0;
}
this is what i tried.
The first step is to read (or set) the large number as a string.
The second step consists in convert this string to a vector of int, each int being less than 10000.
The last step is to calculate a modulo b, in the same way we are performing a division by hand
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
std::vector<int> conver_to_vect_int (const std::string &a) {
std::vector<int> x;
int n = a.size();
x.reserve (n/5 + 1);
for (int i = 0; i < n; i += 5) {
int max = std::min (i+5, n);
std::string s (a.begin() + i, a.begin() + max);
int number = std::stoi (s);
x.push_back (number);
}
return x;
}
int modulo (const std::string &a_string, int b) {
std::vector<int> a = conver_to_vect_int (a_string);
int mod = 0;
for (int val: a) {
int val_with_mod = mod * 100000 + val;
mod = val_with_mod % b;
}
return mod;
}
int main() {
std::vector<std::string> list_s = {"29", "111111111", "111111111111111111111111111111111111", "111111111111111211111111111111111111"};
int b = 9;
for (auto &s: list_s) {
int mod = modulo (s, b);
bool divisibility = mod == 0;
std::cout << "divisibility of " << s << " by " << b << " = " << divisibility << "\n";
}
}

Is there a way avoid a global array?

A lab assignment that I have for a beginner C++ class involves printing the squareroot of a series of numbers stored in an array. The program itself works, but my teacher does not want us to use global variables.
void assignValue(){
for (int x=0; x<10; x++){
int num;
num = rand() % 100 + 1;
if (num % 2 != 0){
num += 1;
}
arr[x] = num;
}
Here's the main method
int main() {
srand(static_cast<unsigned int>(time(0)));
assignValue();
for (int f = 0; f < 10; f++){
cout << f << setw(8) << right << arr[f];
float square = sqrt(arr[f]);
cout << setw(8) << right << fixed << setprecision(3) << square << endl;
}
The arr is a global variable above the main method.
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <cmath>
void assignValue(int arr[], size_t n) {
for (int i=0; i<n; ++i) {
int num;
num = std::rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}
int main() {
const size_t size = 10;
int arr[size];
std::srand(static_cast<unsigned int>(std::time(0)));
assignValue(arr, size);
for (int i = 0; i < size; ++i){
std::cout << i << std::setw(8) << std::right << arr[i];
float square = std::sqrt(arr[i]);
std::cout << std::setw(8) << std::right << std::fixed << std::setprecision(3) << square << std::endl;
}
return 0;
}
Here is a suggestion for the function taking an array reference:
// headers omitted (you'll need additionally iomanip, ctime, cstdlib, cmath)
// The constant is necessary because the function takes
// a reference to an array *of this specific size*
const size_t ARR_SIZE = 10;
// Take a reference to the array (the array is not copied)
void assignValue(int (&arr)[ARR_SIZE])
{
for (int i = 0; i < ARR_SIZE; i++) {
int num = rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}
You call the function simply with
int main()
{
int arr[ARR_SIZE];
// [...]
assignValue(arr);
// ...
}
The following is a more Core Guideline compliant way of doing this as no pointers, or size information is needed.
#include <cstddef>
#include <cstdlib>
template<typename T, std::size_t N>
void assignValue(T (&arr)[N])
{
for (auto &elem : arr) {
elem = rand() % 100 + 1;
if (elem % 2 != 0) {
elem += 1;
}
}
}
auto
main() -> int
{
constexpr const auto ARRAY_SIZE = 10;
int arr[ARRAY_SIZE];
assignValue(arr);
return 0;
}

Print prime factorization in exponential form in C++

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.

Square Root Code C++ without sqrt()

I have to create a code where the user inputs a number which is a perfect square, and I have to show its root. I've made this code, but I'm getting Segmentation Fault 11 , in this piece: int j = squareRootVector[i];
squareRoot.push_back(j);.
I can't change the code too much, so is there a way that I can do that?
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout <<
"Enter the number:\n";
int input;
int number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
cin >> number;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
cout << number << endl;
squareRootVector.push_back(divider);
}
}
for(int i = 0; i < squareRootVector.size(); i++) {
cout << squareRootVector[i] << " ";
/*******PROBLEM*******/
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
/*********************/
}
int root;
for (int i = 0; squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is: " << root << endl;
return 0;
}
The behaviour on accessing squareRootVector[i+1] with i just one below size (which your loop constaint allows) is undefined.
Consider writing
for (std::size_t i = 1; i < squareRootVector.size(); i++) {
instead, and rebasing the for loop body accordingly. I've also slipped in a change of type for i.
Shortly, the problem is that the last cycle in the last "for":
for(int i = 0; i < squareRootVector.size(); i++)
has the following line in it:
squareRootVector[i] == squareRootVector[i+1];
This is an "out of limits" error: squareRootVector only has squareRootVector.size() elements (let's say n), and the elements are indexed from 0 to n-1.
squareRootVector[i+1] in the last cycle points one element after the last one of squareRootVector, which is undefined behavior.
Using vector::iterator is proper way.
for(vector<int>::iterator it = squareRootVector.begin(); it != squareRootVector.end(); ++it)
{
if( (it+1) == squareRootVector.end() )
{
//what to do if there's no next member???
break;
}
if( *it == *(it+1) )
{
squareRoot.push_back(*it);
}
}
Thanks for the answers, guys. I've ended up with this code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Enter the number:\n";
int input = 0;
int number = 0;
cin >> input;
number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
squareRootVector.push_back(divider);
}
}
int vectorSize = squareRootVector.size() - 1;
for(int i = 0; i < vectorSize; i++) {
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
}
int root = 1;
for (int i = 0; i < squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is " << root << endl;
return 0;
}