Getting no output for large inputs in C++ - c++

While the program works as expected on low numbers there is no output when input is big
I tried changing data types to longest there is (unsigned long long) which is more than required yet nothing changed. Changed from cin to scanf just to try but nothing. There is no output no error nothing
I tried v
it is supposed to give the remainder when nth fibonacci number is divided by changing int i to long long as well but no
the said input is 9999999999999 2
#include <iostream>
#include <array>
using namespace std;
int main()
{
int m;
long long n;
scanf("%lli,%i", &n , &m);
int numbers[n];
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
if (numbers[i] >= m)
numbers[i] %= m;
}
cout << numbers[n];
return 0;
}

Related

Multiplying two ridiculously large number stored in an array of chars C++

I have an assignment which requires me to write a program that multiplies two large numbers that are each stored in an array of characters with the maximum length of 100. After countless efforts and debugging and multiplying 10 digit numbers step by step and by hand I have now written the following piece of messy code:
#include <iostream>
#include <string.h>
using namespace std;
const int MAX_SIZE = 100;
int charToInt(char);
char IntToChar(int);
long long int pow10(int);
bool isNumber(char[]);
void fillWith0(char[], int);
void multiply(char[], char[], char[]);
int main(){
char first_num[MAX_SIZE + 1], second_num[MAX_SIZE + 1], product[2 * MAX_SIZE + 1];
cout << "A =\t";
cin.getline(first_num, MAX_SIZE);
cout << "B =\t";
cin.getline(second_num, MAX_SIZE);
multiply(first_num, second_num, product);
cout << "A * B = " << product << endl;
return 0;
}
int charToInt(char ch){
return ch - '0';
}
char intToChar(int i){
return i + '0';
}
long long int pow10(int pow){
int res = 1;
for (int i = 0; i < pow ; i++){
res *= 10;
}
return res;
}
bool isNumber(char input[]){
for (int i = 0; input[i] != '\0'; i++){
if (!(input[i] >= '0' && input[i] <= '9')){
return false;
}
}
return true;
}
void fillWith0(char input[], int size){
int i;
for (i = 0; i < size; i++){
input[i] = '0';
}
input[i] = '\0';
}
void multiply(char first[], char second[], char prod[]){
_strrev(first);
_strrev(second);
if (isNumber(first) && isNumber(second)){
fillWith0(prod, 2 * MAX_SIZE + 1);
int i, j, k;
long long int carry = 0;
for (i = 0; second[i] != '\0'; i++){
for (j = 0; first[j] != '\0'; j++){
long long int mult = (pow10(i) * charToInt(first[j]) * charToInt(second[i])) + carry + charToInt(prod[j]);
prod[j] = intToChar(mult % 10);
carry = mult / 10;
}
k = j;
while (carry != 0){
carry += charToInt(prod[k]);
prod[k] = intToChar(carry % 10);
carry = carry / 10;
k++;
}
}
prod[k] = '\0';
_strrev(first);
_strrev(second);
_strrev(prod);
}
}
My problem is that it does not work with numbers that have more than 10 digits (1234567891 * 1987654321 works fine but nothing with more digits than that), as the output in those cases is a set of weird characters I presume the issue is somewhere something is overflowing and causing weird issues, although I have used long long int to store the only two numeric integers in the algorithm, doing so helped me bump from 6 digits to 10 but nothing more. Is there any suggestions or possibly solutions I can implement?
P.S. : As I mentioned before this is an assignment, so using libraries and other stuff is not allowed, I've already seen this implemented using vectors but unfortunately for me, I can't use vectors here.
The core mistake is using a long long int to store the intermediate multiplied number. Instead, use another char[] so the core of your multiply becomes simply:
for (i = 0; second[i] != '\0'; i++){
char scratch[2 * MAX_SIZE + 1];
// Fill up the first i positions with 0
fillWith0(scratch, i);
// Store second[i] * first in scratch, starting at position i.
// Make sure to 0-terminate scratch.
multiplyArrWithNumber(&scratch[i], intToChar(second[i]), first);
// Add pairwise elements with carry, stop at the end of scratch
addArrays(scratch, prod);
}

My program that should display a N even digit number shows mess

So recently i got a programing task from a contest and my code should display the N
even digit number from 0. In even digit numbers all numbers must be dividable by 2. When i input the number 12 it should show the number 44 on the output but it shous some kind of a mess. here's my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int kturaParzysta = 1;
int N;
cin >> N;
int tab[N];
for(int i = 0; i < N;i++){
string cyfraStr = to_string(N);
bool parzystocyfrowa = true;
for(int j = 0;j <= cyfraStr.length();j++){
if(int(cyfraStr[j]) % 2 != 0){
parzystocyfrowa = false;
}
}
if(parzystocyfrowa){
tab[kturaParzysta] = i;
kturaParzysta++;
}
}
cout << tab[N - 1];
return 0;
}

sum of digits at odd and even places of a string

The output for the variable sum_e is negative which isn't what I expect it to be.
I have simply added the values at even and odd places and stored them in two variables. I checked for solutions and found ones with digit extraction from a number. None of them had a string input.
#include<iostream>
using namespace std;
int main(){
string s;
cin>>s;
int sum_e=0,sum_o=0;
int l=s.length();
for(int i=0;i<=l;i=i+2){
sum_o+=(s[i]-'0');
}
for(int j=1;j<=l;j=j+2){
sum_e+=(s[j]-'0');
}
cout<<sum_o<<endl<<sum_e;
return 0;
}
I subtracted '0' from the string index to convert it into int. One of the variables shows the right output and the other shows a negative one.
Your for loops run one time longer than the length of the array, so when i = l, s[i] will get an undefined/garbage value from memory. Use i < l and j < l rather than i <= l and j <= l, since the index in C++ begins at zero.
#include <iostream>
using namespace std;
int main(){
string s;
cin >> s;
int sum_e = 0, sum_o = 0;
int l = s.length();
for(int i = 0; i < l; i = i + 2){
sum_o += (s[i] - '0');
}
for(int j = 1; j < l; j = j + 2){
sum_e += (s[j] - '0');
}
cout << sum_o << endl << sum_e;
return 0;
}
To improve your code, use one for loop instead of two.
for(int i = 0; i < l; i++){
// Check if even (i%2 returns the remainder of i/2, so here i%2==1 means even)
if(i%2 == 1){
sum_e += (s[i] - '0');
}else{
sum_o += (s[i] - '0');
}
}
Array indexing in C++ starts from 0. You store the length of string as l, so elements of your string lies from s[0] to s[l-1]. At s[l] some garbage value is present which gets added to one of your variables, hence producing undesired results.
#include<iostream>
using namespace std;
int main(){
string s;
cin>>s;
int sum_e=0,sum_o=0;
int l=s.length();
for(int i=0;i<l;i=i+2){ // use <
sum_o+=(s[i]-'0');
}
for(int j=1;j<l;j=j+2){ // use <
sum_e+=(s[j]-'0');
}
cout<<sum_o<<endl<<sum_e;
return 0;
}
You can also do your odd and even position sum using a single loop. Your code size will reduce and look better
for(int i=0;i<l;i=i+2){
if(i%2==0)// even index means odd position numbers
sum_o+=(s[i]-'0');
else
sum_e+=(s[j]-'0');
}

Large digit numbers

The program is simple. The user inputs n and n amount of numbers and i try to add zeros in between adjacent digits. For example if the user enters 9(n) digits as 1 2 3 4 5 6 7 8 9 (spaced out), the program outputs 10203040506070809. The program works well for up to n=8 digits but i get funny answers from n=9 digits upwards. The range of n should be 3<=n<=15 . My program is as follows:
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<long long>nums;
int en = n;
while (en > 0)
{
long long x;
cin >> x;
nums.push_back(x);
--en;
}
int r = 2 * n - 2;
long long new_val = 0;
int j = 0;
for (int i = 0; i < n; ++i)
{
new_val = new_val + nums[i] * (pow(10, r - j));
j += 2;
}
cout << new_val << endl;
}
I don't know how to solve the issue of funny answers from n=9 to n=15.
The main problem is long long is only 64-bits in size, and thus can only hold up to 19 digits. Its maximum value is 9,223,372,036,854,775,807.
It is possible to make your code work correctly up to n=10 if you simply remove pow() (which operates on floating-point types, not integer types). For the 2nd and subsequent loop iterations, you can simply multiply new_val by 100 before adding nums[i]:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<long long> nums;
int en = n;
while (en > 0)
{
long long x;
cin >> x;
nums.push_back(x);
--en;
}
long long new_val = 0;
if (n > 0)
{
new_val = nums[0];
for (int i = 1; i < n; ++i)
{
new_val *= 100;
new_val += nums[i];
}
}
cout << new_val << endl;
}
Live Demo
However, 1020304050607080901 is 19 digits, so n>=11 will overflow past the max value of long long.
Live Demo
For such high values, you need to use a BigNumber library (as most compilers do not yet have a native 128-bit numeric type). Or, just use std::string instead of long long:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
cout << "\nEnter n and n values: \n";
int n;
cin >> n;
vector<int> nums;
int en = n;
while (en > 0)
{
int x;
cin >> x;
nums.push_back(x);
--en;
}
ostringstream new_val;
if (n > 0)
{
new_val << nums[0];
for (int i = 1; i < n; ++i)
new_val << '0' << nums[i];
}
cout << new_val.str() << endl;
}
Live Demo
Allow me to suggest a different approach to this problem. Since containers will give you trouble holding those large numbers, then don't with them as numbers, try string instead:
After you get the numbers from the user and store them in the nums vector, do the following:
string output = "";
char temp;
for (int i = 0; i < nums.size(); i++){
temp = nums [i] + '0';
output += temp;
if (i != (nums.size()-1))
output += "0";
}
cout << output;
Using this method, the user can enter any number as large as they want. If you want the number to be from 9 to 15, you can simply add validation at the beginning without having to deal with complicated containers.

Multi-threading using vectors causing runtime errors

I am working on a assignment where I need to calculate the frequency of prime numbers from 1 to 10 million. we are to do this by taking variable U (which is 10 million) and dividing it into N parts and have multiple threads calculate the frequency of prime numbers, we must try this with different values for N and observe our proccessor ticks and time taken to calculate. I thought the best way to do this is with vectors, and the professor recommended it. however when I run my code, I get two run-time errors, first one being "Vector Subscript out of range" and the second one "standard C++ Libraries out of range && 0" . i checked to see if i went out of bounds in the vectors some where but it does not seem that I have. below is the code. thanks for taking a look and any feedback is greatly appreciated
#include <iostream>
#include <thread>
#include <vector>
#include<algorithm>
#define MILLION 1000000
using namespace std;
using std::for_each;
void frequencyOfPrimes(long long upper, long long lower, long long* freq)
{
long long i, j;
*freq = upper - 1;
for (i = lower; i <= upper; ++i)
for (j = (long long)sqrt(i); j>1; --j)
if (i%j == 0) { --(*freq); break; }
return;
}
int main(int argc, char* argv[])
{
clock_t ticks = clock();
long long N = 5;
long long U = 10*MILLION;
long long F=0;
long long d = U / N;
vector<thread> tV;
vector<long long> f, u, l;
for (int i = 0; i<N; i++) {
if (i == 0) {
l.push_back(2);
u.push_back(d);
}
else {
l.push_back(u[i - 1] + 1);
u.push_back(u[i - 1] + d);
}
}
l[N - 1] = U;
for (int i = 0; i < N; i++) {
tV.push_back(thread(frequencyOfPrimes, u[i], l[i], &f[i]));
}
for_each(tV.begin(), tV.end(), mem_fn(&thread::join));
ticks = clock() - ticks;
for (int i = 0; i < N; i++)
F = f[i] + F;
cout << "Frequency is " << F << endl;
cout << "It took " << ticks << " ticks (";
cout << ((float)ticks) / CLOCKS_PER_SEC << " seconds)" << endl;
this_thread::sleep_for(chrono::seconds(5));
return 0;
}