Why this code doesn't allow me to receive the whole array? - c++

#include <bits/stdc++.h>
using namespace std;
string bin(int n){
string x="";
while(n!=0)
{
int z=n%2;
x+=to_string(z);
n%=2;
}
return x;
}
int main(){
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
string x=bin(a[i]);
int u=x.size();
int cnt=0;
for(int g=0;g<u;g++)
{
if(x[g]=='1')
++cnt;
}
cout<<cnt<<' ';
}
cout<<'\n';
}
}
This code is given several test cases and each test case will have an array of n integers, for each element in the array I should count the number of ones in the binary representation of it. I wrote a function that expects an integer and returns a string containing the binary representation of it. But I wonder why my code does not end, and not allowing me to receive other numbers in array.
For instance, there's one test case and and only array of 2 integers if I inputted 1 and wait for ever to enter the second number, what's happening?

This is your bin function reduced to the bare minimum:
string bin(int n){
while(n!=0)
{
n%=2;
}
return {};
}
If n is even you will set it to 0 on the first iteration, otherwise you set it to 1 and never change it afterwards (1%2==1). Hence you have a endless loop. I won't spoil you the "fun" of completing the exercise, so I will just point you to using a debugger. If you step trough your code line by line you could have observed how n never changes and why the loop wont stop.
PS: (spoiler-alert) you might want to take a look at std::bitset (end of spoiler)

Related

Why am I getting a 'Runtime Error - SIGSEGV' in my code?

I have got some impossible queries for you! (or are they? ;) )
You have n binary numbers of length m. The ith binary number is Bi. Also, you have to perform q queries on them. The indexing is zero-based and the indexing of bits starts from left.
The queries are of type : a, i, j.
If a is:
0 : perform Logical AND operation between Bi and Bj and output the number of 1s in the result.
1 : perform Logical OR operation between Bi and Bj and output the number of 1s in the result.
2 : perform Logical XOR operation between Bi and Bj and output the number of 1s in the result.
3 : flip the value of the jth bit of Bi (i.e. set the bit to 0 if it equals 1 and vice-versa).
Note: For queries of type 0, 1, and 2, the binary numbers remain unchanged.
It is also recommended to use Fast I/O for C++ and JAVA programmers.
Input Format:
First line contains Integers n and m.
The next n lines contain binary numbers of length m.
The ith line contains binary number Bi.
The next line contains an integer q
The next q lines contain queries of type : a, i, j.
Output Format:
Output number of 1s in the result of type 0, 1 and 2 queries.
Constraints:
1<=n, m<=2500
1<=q<=10^6
I have tried changing the array size, but still the error remains the same!
#include <iostream>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,m;
cin>>n>>m;
char arr[3000][3000];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin>>arr[i][j];
}
long int q;
cin>>q;
char query[3000][3000];
for(long int k=0;k<q;k++)
for(long int l=0;l<3;l++)
{
cin>>query[k][l];
}
for(long int i=0;i<q;i++)
{
if(int(query[i][0]-48)==3)
{
if(arr[int(query[i][1])-48][int(query[i][2])-48]=='1')
{
arr[int(query[i][1])-48][int(query[i][2])-48]='0';
}
else
{
arr[int(query[i][1])-48][int(query[i][2])-48]='1';
}
}
else if(int(query[i][0]-48)==2)
{
int cntr=0;
int bi=int(query[i][1])-48;
int bj=int(query[i][2])-48;
for(int i=0;i<m;i++)
{
int xorres=arr[bi][i]^arr[bj][i];
if(xorres==1)
cntr++;
}
cout<<cntr<<endl;
}
else if(int(query[i][0]-48)==1)
{
int cntr=0;
int bi=int(query[i][1])-48;
int bj=int(query[i][2])-48;
for(int i=0;i<m;i++)
{
int andres=arr[bi][i]|arr[bj][i];
if(andres-48==1)
cntr++;
}
cout<<cntr<<endl;
}
else if(int(query[i][0]-48)==0)
{
int cntr=0;
int bi=int(query[i][1])-48;
int bj=int(query[i][2])-48;
for(int i=0;i<m;i++)
{
int andres=arr[bi][i]&arr[bj][i];
if(andres-48==1)
cntr++;
}
cout<<cntr<<endl;
}
}
return 0;
}
The two char[3000][3000]'s that you allocate on the stack is the reason for the crash.
Since there's no upper constraint on n you'd better to try to allocate it on the heap and catch the exception if it fails. This can be done by using std::vector<std::vector<char>> instead.
Replace:
int n,m;
cin >> n >> m;
char arr[3000][3000];
With something like this:
#include <vector>
size_t n, m;
std::vector<std::vector<char>> arr;
while(std::cin >> n >> m) {
try {
arr.resize(n, std::vector<char>(m));
break; // success, break out of the while-loop
} catch(const std::exception& ex) {
// exception caught, most probably a bad_alloc
std::cerr << ex.what() << " ... try again\n";
}
}
As proposed in the comments, you probably don't need to store all the queries. Just deal with one query at a time.
Also, never #include <bits/stdc++.h> yourself. It's a non-standard/non-portable header file that includes a lot more than you need, and often not all you need. Instead, only include the headers you actually need.
Similarly, using namespace std; is considered bad practice.
OK, so I think you have complicated some things here.
The size of the queries is 10^6 and you are declaring the array as query[3000][3000].
Now, I don't think you need to store the queries. Consider this-
cin>>q;
while(q--)
{
cin>>a>>i>>j;
/*Your code here*/
}
The question states that the queries are in the form : a i j
So for example if you want to perform operation 0 on first 2 strings, the query will be:
0 1 2
But you are storing the binary numbers from index 0!
So, your code will perform the operation on second and third query. So, what you need to do is just take subtract 1 from values of i and j.

Reversing an Array Results In SegFault

#include <iostream>
using namespace std;
/*
*
*/
int main() {
int k, in[k],reversea[k],i,m,n;
cin>>k;
for (i=0;i<k;i++){
cin>>in[i];
}
for (m=k-1;m>=0;m--){
for (n=0;n<k;n++){
in[m]=reversea[n];
}
}
for(i=0;i<k;i++){
cout<<reversea[i];
}
return 0;
}
I have no idea why it says segmentation fault even before i start debugging it. I compile another one on calculating the frequency of 1, 5, and 10 in an array of k numbers, and it says the same thing...
Here is the other one:
#include <iostream>
using namespace std;
int main() {
int k,i,m,n,count5,count1,count10;
int input[k];
cin>>k;
for (i=0;i<k;i++){
cin>>input[i];
}//input all the numbers
for(i=0;i<k;i++){
if (input[i]=1){
count1++;
}
if (input[i]=5){
count5++;
}
if (input[i]=10){
count10++;
}
}
cout<<count1<<"\n"<<count5<<"\n"<<count10<<"\n";
return 0;
}
Please help me. Thanks.
On this line
int k, in[k],reversea[k]
How are you supposed to initialize an array with k elements if k isn't initialized? The size of an array must be known at compile time not run time. If k isn't know until run time, use a std::vector
int k;
std::cin >> k;
std::vector<int> in(k);
std::vector<int> reversea(k);
Both your programs have two major faults.
You need to know the size of an array while creating it. In your code, k is still uninitialized and you are using this value as the size of your array. Instead, change it to
int k,i,m,n;
cin >> k;
int in[k];
int reversea[k];
While reversing the array, you should be filling reversea using values from in, and not the other way round. Also, you don't need 2 for loops, just use 1 for loop.
for (m=k-1; m>=0; m--){
reversea[m] = in[k-1-m];
}
In the second program, you again need to get the value of k before creating the array input[k].
You are testing for equality with a = instead of == . Change your code from
if (input[i]=1){
to
if (input[i] == 1) {

LeetCode TwoSum solution not working

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
int bins(int* p,int lo,int hi,int t)
{//BinarySearch
int mid=0;
int c=0;
if(lo<hi)
{
mid=(lo+hi)/2;
if(p[mid]==t) c=1;
else if(t>p[mid])
bins(p,mid+1,hi,t);
else if(t<p[mid])
bins(p,0,mid,t);
}
return c;
}
int main()
{
clrscr();
int target;
int k;
int count=0;
cout<<"Enter the number of elements:";
cin>>k;
int* numbers=new int(k);
cout<<"Enter the target element"<<endl;
cin>>target;
cout<<"Enter the elements:"<<endl;
for(int i=0;i<k;i++)
cin>>numbers[i];
int* nu=new int(k);
memset(nu,0,sizeof(int));
/*for(i=0;i<k;i++){
cout<<numbers[i]<<endl;
}*/
for(i=0;i<k;i++)
{
int bool=bins(nu,0,k,numbers[i]);
//printf("%d\n",bool);
if(bool)
{
count++;
}
else
{
int tg=target-numbers[i];
cout<<"targetval:"<<tg<<endl;
nu[i]=tg;
}
//bool?count++:(nu[i]=target-numbers[i]);
}
cout<<"Count is:"<<count<<endl;
getch();
return 0;
}
this is the code i have written for TwoSum problem in leetcode,instead of using HashMap whose time complexity is O(n) i used binary search whose complexity is O(logn)
The problem i'm facing is the input i give to the array numbers[i] takes only 3 values and from then it stores junk values even after assigining proper inputs from console
this program has been compiled succesfully on Turbocompiler on system
int* numbers=new int[k];////allocates an array of k adjacent integers. (undefined values)
You are allocating for an array. Check the notations.
Also you are using a keyword as a variable.(bool).
What have you done?
int *numbers=new int(k);////allocates an integer, set to k. (same syntax as constructors)
Leetcode doesn't give exact code. It will have syntax errors or compilation erros. You have to fix them to make it work. In this case, following are the issues,
int* numbers=new int[k]; //not int* numbers=new int(k);
Another thing is that bool is a keyword, that is used to give true or false for variables. You have to use another variable.

C++ Reverse a number of any length

I want to reverse the number given by the user. I wrote the code in such a way that it takes the number of digits of number and the input and reverses it. As even the limit of 'long long' is 19 digits, what can I do so that the code works even if the number of digits in the input are greater than 20? [Without using third party libraries]
#include<iostream>
using namespace std;
void make_int(int a[],long long int n)
{
int i=0;
while(n)
{
a[i]=n%10;
i++;
n=n/10;
}
for(int j=0;j<i;j++)
cout<<a[j];
}
int main()
{
int N;
cin>>N;
int *tc = new int[N];
long long int num;
cin>>num;
make_int(tc,num);
return 0;
}
Read the number in as a std::string and reverse that, since it's actual numerical value is unimportant for what you want to do.

The following prime generator code shows an error when i want prime numbers greater than 1000000.Why?

The following prime generator code shows an error when i want prime numbers greater than 1000000.Why??
at first it seemed to occur b'cuz of int so i changed it to long but the error is still there....
technically speaking it nit an error the program after running displays the message "primegen.exe has stopped working"
#include <iostream>
using namespace std;
int main()
{
long int a,c,k,d;
k=0;
cin>>a;
cin>>d;
long int b[a];
b[a-1]=0;
for(long int i=2;i<=a;i++)
{
for(long int j=2;j<=(i/2);j++)
{
c=1;
if ( i%j!=0 )
{
continue;
}
else
{
c=0;
break;
}
}
if (c!=0)
{
b[k]=i;
//++k;
}
else b[k]=0;
++k;
}
for(long int i=d;i<a;i++)
{
if (b[i]!=0)
{
cout<<b[i]<<"\t";
}
}
cin.ignore();
cin.get();
return 0;
}
There is no error in this code.
The code is too slow though, it is almost quadratic. The projected time to reach 1 mln on ideone: 290 seconds.
After fixing it, by changing the inner for loop condition from for(...;j<=(i/2);...) to for(...;j<=(i/j);...), it runs at ~ n^1.45, empirically, and reaches 1 mln in 1.27 seconds, on Ideone.
Defining a static array won't help in this case. Because you're not allowed to declare such a long static array in C++;
You might want to try
int *b = new int [a];
declaring the array size dynamically (i.e the array size will be decided at run time). The code should work until variable 'a' exceeds the range of int (–2,147,483,648 to 2,147,483,647).