Can anyone explain what is the error I am getting in the output and how to remove it? - c++

My code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int BinaryToDecimal(int n)
{
int ans = 0;
int x = 1;
while (n > 0)
{
int y = n % 10;
ans = ans + x * y;
x = x * 2;
n = n / 10;
}
return ans;
}
int DecimalToBinary(int num)
{
vector<int> vect;
while (num > 0)
{
vect.push_back(num % 2);
num = num / 2;
}
int s = vect.size();
int i = s - 1;
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
return vect.at(i);
}
int main()
{
int a, b;
cout << "Enter first number: " << endl;
cin >> a;
cout << "Enter second number: " << endl;
cin >> b;
int a_deci = BinaryToDecimal(a);
int b_deci = BinaryToDecimal(b);
int sum = a_deci + b_deci;
DecimalToBinary(sum);
cout << endl;
return 0;
}
Output:
Enter first number:
10101
Enter second number:
11010
101111terminate called after throwing an instance of 'std::out_of_range'what(): vector::_M_range_check: __n (which is 18446744073709551615) >= this->size() (which is 6)
What does this error message mean and how do I fix it?

After this for loop
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
the variable i is equal to -1.
So the next call of the member function at with the value equal to -1 (that yields a very big number of the unsigned type std::vector<int>::size_type)
return vect.at(i);
throws the exception.
It seems you need to return from the function the whole vector elements of which will represent a number in the binary form.
Instead of the container std::vector<int> it will be better to use std::bitset.

Related

Extra "0" in output when factorizing a number

Write a function int fact(int n) which displays the factors of the integer n, and returns the number of factors. Call this function in main() with user input
#include<iostream>
using namespace std;
int fact(int n);
int main() {
int n,factor;
cout << "Enter an integer : ";
cin >> n;
factor = fact(n);
cout << factor;
return 0;
}
int fact(int n)
{
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
cout << i << endl;
}
return 0;
}
If I enter 7, I get 1,7,0 . How do i remove this 0 and how do i find the number of factors?
You should count in your int fact() function. Set a variable to 0 and increment each time you currently display i. Then at the end of the function instead of returning 0 return the count variable.
int fact(int n)
{
int count=0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
count++;
}
}
return count;
}
The key part is "and returns the number of factors". You don't do that. Keep a count of the factors:
int fact(int n)
{
int count = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
{
// found a factor, add to the count
count++;
cout << i << endl;
}
}
// return the count instead
return count;
}
Then, your main function can use that count:
factor = fact(n); // fact(n) will already print the factors
// now just print the number
cout << "Number of factors: " << factor << '\n';
#include <iostream>
#include <vector>
std::vector<int> fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
std::vector<int> factors = fact(n);
for (auto i : factors) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "Number of factors: " << factors.size() << '\n';
return 0;
}
std::vector<int> fact(int n) {
std::vector<int> vec{1};
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
vec.push_back(i);
}
}
vec.push_back(n);
return vec;
}
If you're going to return anything from fact(), it should be the factors. To do so, I am using a std::vector. It is an array that can grow on demand. The numbers 1 and n are always factors, so I don't bother doing the math for them. The vector is initialized already holding the value 1, and I only calculate numbers up to and including half of n (Anything greater than n/2 won't divide evenly, so my loop is finished about half as fast by recognizing the actual range). I then just add n to the vector, which I return.
My main prints the vector, and the vector knows its own size, which is the number of factors.
Alternatively, you can just keep a count in your fact() function.
#include <iostream>
#include <vector>
// Prints factors of n and returns the number of factors
int fact(int n);
int main() {
int n;
std::cout << "Number: ";
std::cin >> n;
int numFactors = fact(n);
std::cout << "Number of factors: " << numFactors << '\n';
return 0;
}
int fact(int n) {
int factorCount = 2; // Already counting 1 and n
std::cout << "1 ";
for (int i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
std::cout << i << ' ';
++factorCount;
}
}
std::cout << n << '\n';
return factorCount;
}
The main problem with your code is that your function always returns zero. You need to keep a count of factors and return it.
Besides that your code performance badly as the loop goes on much longer than needed. You can use the square root of n as the limit in the for loop. Like:
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int limit = sqrt(n);
for (int i = 1; i <= limit; ++i)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
}
if (limit * limit == n)
{
--res;
}
return res;
}
For n = 36 the output is:
1 - 36
2 - 18
3 - 12
4 - 9
6 - 6
and the returned value is 9
Below is another approach. It doesn't use square root. Instead it keeps the number of loops low by using the square of i as loop limit.
int fact(int n)
{
if (n < 1) return 0;
int res = 0;
int i = 1;
int i_square = i * i;
while (i_square < n)
{
if (n % i == 0)
{
res += 2;
cout << i << " - " << n/i << endl;
}
++i;
i_square = i * i;
}
if (i_square == n)
{
++res;
cout << i << " - " << n/i << endl;
}
return res;
}
Fact() always returns 0 so this line print 0
cout << factor;
for the number of factors you can change the return value of fact() :
int fact(int n)
{
int nb = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0) {
cout << i << endl;
nb++;
}
}
return nb;
}

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.

Run-Time Check Failure #2 - Stack around the variable 'k' was corrupted

an exercise:find out the perfect number from 1 to 1000
(perfect number:such as 6,because 6=1+2+3)
this is my code.
#include<iostream>
using namespace std;
int main()
{
int k[11];
int i, a, n, s;
for (a = 2; a <= 1000; a++)
{
n = 0;
s = a;
for (i = 1; i < a; i++)
if (a%i == 0)
{
n++;
s = s - i;
k[n] = i;
}
if (s == 0)
{
cout << a << " is a perfect number" << endl;
cout << "its factors are:";
for (i = 1; i <= n; i++)cout << k[i] << " ";
cout << endl;
}
}
return 0;
}
but it shows Run-Time Check Failure #2 - Stack around the variable 'k' was corrupted
when I change int k[11]to int k[32] it is correct.
the array element is at least 32 ,so why?
Array indices start at 0. You are incrementing n too early. And obviously, 10 is too small as the array size. What formula gives this size?

C++ : Recursion (Variables losing value)

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.

Taking in multiple inputs at once and then giving out output at once [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So my question is how to efficiently write a program where in we are able to take multiple inputs (the amount of inputs given is determined by the user) and then give the outputs at once. Lets consider a program which gives gives the sum of its digits. Eg - 12345 = 15.
//Single input single output
#include <iostream>
using namespace std;
int main()
{
int T, N;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
cout << "Enter the value of N : " << endl;
while (T > 0)
{
cin >> N;
int ans = 0,temp1,temp2;
while(N!=0)
{
temp1= N %10;
N = (N - temp1)/10;
ans = ans + temp1;
}
cout << ans << endl;
T--;
}
return 0;
}
// Taking in all inputs then giving out all outputs ( Not working properly)
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase, int t);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int *Ans(new int[T]);
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i, T);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
delete[] Ans;
return 0;
}
int SumCal(int Number, int TestCase, int t)
{
int temp1, temp2 = 0;
int *AnsTemp(new int[t]);
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
AnsTemp[TestCase] = (temp1 + temp2);
while (temp2 > 10)
{
AnsTemp[TestCase] = (AnsTemp[TestCase] + temp1);
temp2 = temp2 / 10;
temp1 = temp1 % 10;
}
return AnsTemp[TestCase];
delete[] AnsTemp;
}
// This will work properly for multiple inputs multiple outputs
#include <iostream>
using namespace std;
int SumCal(int Number, int TestCase);
int main()
{
int N, T;
cout << " Enter the value of T ( Total number of test cases) " << endl;
cin >> T;
int Ans[1000] = {};
if (T >= 1 && T <= 1000)
{
cout << "Enter the value of N" << endl;
for (int i = 1; i <= T; i++)
{
cin >> N;
if (N >= 1 && N <= 100000)
Ans[i] = SumCal(N, i);
}
}
for (int z = 1; z <= T; z++)
{
cout << Ans[z] << endl;
}
return 0;
}
int SumCal(int Number, int TestCase)
{
int temp1, temp2 = 0;
int ans;
temp1 = Number % 10;
temp2 = Number / 10;
if (temp2 < 10 && temp2 > 0)
ans = (temp1 + temp2);
while (temp2 > 10)
{
ans = (ans + temp1);
temp2 = temp2 / 10;
temp1 = temp2 % 10;
}
return ans;
}
These are the codes I could think of. The first one is a simple one, which takes in an input and then gives out a output. In the second one I tried to use dynamic memory allocation but the program gives error. ( I know I haven't made proper use of * and & in it but I already tried using it in various manners and failed). The third program is successful but as we are setting up a large constraint value to the array, (i.e int Ans[1000]) it makes the program a bit inefficient.
So my question is how would one dynamically allocate memory during runtime successfully to take in multiple inputs and then give multiple outputs at once.
It's very hard to work with your code. I just took the 1st example, minimized the code and did what you should have done:
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int T;
cout << "Enter the value of T (No. of test cases)" << endl;
cin >> T;
int *buf = new int[T](); // buffer to hold the answers
for(int i = 0; i < T; ++i)
{
int N;
cout << "Enter the value of N : " << endl;
cin >> N;
while(N)
{
buf[i] += N % 10; // calculate on the buffer element
N /= 10;
}
}
for(int i = 0; i < T; ++i)
cout << buf[i] << endl; // print the buffer
delete [] buf; // delete buffer
return 0;
}
There's not much to do for managing the dynamically allocated array here, but take a look at std::vector and its uses.