I've written some code to calculate LCM for 3 numbers. My question is:
why with line:
std::cout << "";
code does work, and without this line code doesn't work?
How it is possible that printing some text on screen, can affect on how program works? It is a matter of some buffering or smth. like this?
#include <iostream>
int NWD(int a, int b){
int r;
while (r != 0){
if (a>b)
r = a-b;
else
r = b-a;
a = b;
b = r;
}
return a;
}
int NWW(int a, int b){
std::cout << ""; // without this code doesn't work
return a*b/ (NWD(a,b));
}
int NWW3(int a, int b, int c){
return NWW(c, NWW(a,b));
}
int main()
{
cout << NWW3(1,7,9);
}
In your NWD() function:
int NWD(int a, int b){
int r; // <-- notice this
while (r != 0){
if (a>b)
r = a-b;
else
r = b-a;
a = b;
b = r;
}
return a;
}
You declare r, but you didn't assign any value to r, so r is now uninitialized.
Then, you compare r with 0 in r != 0. Because r is uninitialized, this cause undefined behaviour. Undefined behaviour can do anything, from still running normally to crashing the program.
A quick fix to this problem is to initialize r with a non-zero value:
int r {-1};
Another issue is in main():
int main()
{
cout << NWW3(1,7,9);
}
It should be:
int main()
{
std::cout << NWW3(1,7,9);
}
In your main function, you have cout declared, but have not included the standard namespace along with it, like you have done on in your NWW function.
So it should look like
int main()
{
std::cout << NWW3(1,7,9);
}
You could also include " using namespace std; " under the header files.
This fills in the std:: for you as it pulls cout from its list of predefined features.
Related
Seriously, I don’t remember..
Would an integer work??
But I don’t know why its not working...
I'm trying to add integers, like this.
int main() {
i = 1;
b = 3;
}
Signed int addition() {
i + b
}
You can't use functions and variables, including local variables, parameters, etc before they have been declared first. Though, you can initialize variables at the same time you declare them. For example:
#include <iostream>
int addition(int a, int b);
int main() {
int i = 1;
int b = 3;
int sum = addition(i, b);
std::cout << sum;
}
int addition(int a, int b) {
return a + b;
}
You have a lot of syntax errors in that code. Until you are more comfortable with programming, just start with a simple working "Hello world" example, and add one line of code at a time, compiling after each line you add. Look carefully at the error messages the compiler gives you and fix them before adding another line. You might arrive at something like this:
int main() {
int i = 1;
int b = 3;
return i + b;
}
When you run this and check the process return code (e.g. using$? in Bash) then you would get 4.
It should not be hard.
// [...]
int Add(int x, int y) { return x + y; }
using namespace std;
int main(void) {
int a = 1, b = 2;
printf("%d\n", Add(a + b));
return 0;
}
I tried to write quicksort by myself and faced with problem that my algorithm doesn't work.
This is my code:
#include <iostream>
#include <vector>
using namespace std;
void swap(int a, int b)
{
int tmp = a;
a = b;
b = tmp;
}
void qsort(vector <int> a, int first, int last)
{
int f = first, l = last;
int mid = a[(f + l) / 2];
do {
while (a[f] < mid) {
f++;
}
while (a[l] > mid) {
l--;
}
if (f <= l) {
swap(a[f], a[l]);
f++;
l--;
}
} while (f < l);
if (first < l) {
qsort(a, first, l);
}
if (f < last) {
qsort(a, f, last);
}
}
int main()
{
int n;
cin >> n;
vector <int> a;
a.resize(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
qsort(a, 0, n - 1);
for (int i = 0; i < n; i++) {
cout << a[i] << ' ';
}
return 0;
}
My sort is similar to other that described on the Internet and I can't find where I made a mistake.
Even when I change sort function, the problem was not solved.
You don't pass qsort the array you want to sort, you pass it the value of that array. It modifies the value that was passed to it, but that has no effect on the array.
Imagine if you had this code:
void foo(int a)
{
a = a + 1;
}
Do you think if I call this like this foo(4); that foo is somehow going to turn that 4 into a 5? No. It's going to take the value 4 and turn it into the value 5 and then throw it away, since I didn't do anything with the modified value. Similarly:
int f = 4;
foo(f);
This will pass the value 4 to foo, which will increment it and then throw the incremented value away. The value f has after this will still be 4 since nothing ever changed f.
You meant this:
void qsort(vector <int>& a, int first, int last)
Your swap has the same problem. It swaps the values of a and b, but then never does anything with the value of a or b. So it has no effect. How could it? Would swap(3, 4); somehow change that 3 into a 4 and vice-versa? What would that even mean?
Your swap does not swap anything. You should write tests not only for the whole program but for as small pieces as possible. At least you should test single functions. Try this:
int main() {
int a= 42;
int b= 0;
std::cout << "before " << a << " " << b << "\n";
swap(a,b);
std::cout << "after " << a << " " << b << "\n";
}
This is "poor mans testing". For automated tests you should use a testing framework.
Then read about pass by reference. (While doing so you hopefully also realize the issue with not passing the vector to qsort by reference.)
Then use std::swap instead of reinventing a wheel.
I Found two error on your code
void swap(int a, int b) This method is not working, cause is receive value only and swap , but the original one is not updated.
void swap(int *a, int *b)
{
int t;
t = *b;
*b = *a;
*a = t;
}
swap(&a, &b);
And you pass vactor which also pass value. replace your void qsort(vector <int> &a, int first, int last) method.
This is my code for finding the longest collatz sequence between 1 and n. And obviously for t test cases. Here, I have also used memoization and thus malloced 'v'. But as the input to the function cycles(int x) goes beyond 4254, ie. 4255, there is something peculiar happening. The function is being input a number 6053452 instead of 4255. And due to this, the program segfaults, as we have only allocated space for 5000000 integers. What have I done wrong?
Note: The program works pleasantly till n = 4254! (not the factorial)
#include <iostream>
#include <cstdlib>
#define RANGE 5000000
using namespace std;
int *v = (int*)malloc(sizeof(int)*RANGE);
int cycles(int x){
int c = 1;
while(x!=1){
if(v[x]!=0){
c = c + v[x];
break;
}
if(x%2){
x = 3*x + 1;
}else{
x/=2;
}
c++;
}
v[x] = c;
return c;
}
void solve(int n){
int mx = 0;
int mx_cnt = 0;
int c;
for(int i=1;i<=n;i++){
c = cycles(i);
if(c >= mx_cnt){
mx = i;
mx_cnt = c;
}
}
cout << mx << endl;
}
int main(){
int t,n;
cin >> t;
while(t--){
cin >> n;
solve(n);
}
return 0;
}
The main problem that you observe is that you access v out of bounds. You also use the mallocd memory uninitialized which makes the program have another problem. Both results in undefined behavior.
int cycles(int x){
int c = 1;
while(x!=1){
if(v[x]!=0){ // <- x >= RANGE
c = c + v[x];
break;
}
// ...
To find problems like this I suggest using a vector instead and, at least when developing the program, use the vector::at() bounds checking member function.
std::vector<int> v(RANGE);
int cycles(int x){
int c = 1;
while(x!=1){
// The below use of `v.at(x)` may result in an exception like:
// what(): vector::_M_range_check:
// __n (which is 6053452) >= this->size() (which is 5000000)
if(v.at(x)!=0){
c = c + v[x];
break;
}
// ...
To catch the exception, you could rewrite main like this:
#include <exception>
int main() {
int t, n;
try {
std::cin >> t;
while(t--) {
cin >> n;
solve(n);
}
} catch(const std::exception& ex) {
std::cout << "Exception: " << ex.what() << '\n';
}
}
If you have a modern 64 bit computer, allocating a lot more shouldn't be a problem. I did this and it solved 4255 fine:
constexpr size_t RANGE = 6810137;
v points to a malloced array and malloc does no initialization. You have if(v[x]!=0) and c = c + v[x]; operating on an uninitialized variables. Embrace C++ and replace the malloced array with a std::vector. vector initializes its contents.
This might not be the only bug, just the most obvious.
Correction based on point raised by molbdnilo in the comments: I reached for too complicated a tool. int v[RANGE]; will allocate and zero-initialize the array. Since the array never changes size, a vector's dynamic array is unnecessary. Use std::array<int, RANGE> v; and you'll have a zero-initialized fixed-size array and still get useful functions like at for debugging.
I am self-studying C++ and the book "Programming-Principles and Practices Using C++" by Bjarne Stroustrup. One of the "Try This" asks this:
Implement square() without using the multiplication operator; that is, do the x*x by repeated addition (start a
variable result at 0 and add x to it x times). Then run some version of “the first program” using that square().
Basically, I need to make a square(int x) function that will return the square of it without using the multiplication operator. I so far have this:
int square(int x)
{
int i = 0;
for(int counter = 0; counter < x; ++counter)
{
i = i + x;
}
return i;
}
But I was wondering if there was a better way to do this. The above function works, but I am highly sure it is not the best way to do it. Any help?
Mats Petersson stole the idea out of my head even before I thought to think it.
#include <iostream>
template <typename T>
T square(T x) {
if(x < 0) x = T(0)-x;
T sum{0}, s{x};
while(s) {
if(s & 1) sum += x;
x <<= 1;
s >>= 1;
}
return sum;
}
int main() {
auto sq = square(80);
std::cout << sq << "\n";
}
int square(int x) {
int result = { 0 };
int *ptr = &result;
for (int i = 0; i < x; i++) {
*ptr = *ptr + x;
}
return *ptr;
}
I am reading that book atm. Here is my solution.
int square(int x)
{
int result = 0;
for (int counter = 0; counter < x; ++counter) result += x;
return result;
}
int square(int n)
{
// handle negative input
if (n<0) n = -n;
// Initialize result
int res = n;
// Add n to res n-1 times
for (int i=1; i<n; i++)
res += n;
return res;
}
//Josef.L
//Without using multiplication operators.
int square (int a){
int b = 0; int c =0;
//I don't need to input value for a, because as a function it already did it for me.
/*while(b != a){
b ++;
c = c + a;}*/
for(int b = 0; b != a; b++){ //reduce the workload.
c = c +a;
//Interesting, for every time b is not equal to a, it will add one to its value:
//In the same time, when it add one new c = old c + input value will repeat again.
//Hence when be is equal to a, c which intially is 0 already add to a for a time.
//Therefore, it is same thing as saying a * a.
}
return c;
}
int main(void){
int a;
cin >>a;
cout <<"Square of: "<<a<< " is "<<square(a)<<endl;
return 0;
}
//intricate.
In term of the running time complexity,your implementation is clear and simply enough,its running time is T(n)=Θ(n) for input n elements.Of course you also can use Divide-and-Conquer method,assuming split n elements to n/2:n/2,and finally recursive compute it then sum up two parts,that running time will be like
T(n)=2T(n/2)+Θ(n)=Θ(nlgn),we can find its running time complexity become worse than your implementation.
You can include <math.h> or <cmath> and use its sqrt() function:
#include <iostream>
#include <math.h>
int square(int);
int main()
{
int no;
std::cin >> no;
std::cout << square(no);
return 0;
}
int square(int no)
{
return pow(no, 2);
}
I have a code that searches for a given entry in an array, and returns the position in the array of that entry, provided one knows the array contain that number. However, a strange thing happens. When I try to test the code with some concrete arrays, the code works well for some entries, and it does not work for others. The code is this:
#include <iostream>
#include <cmath>
using namespace std;
int Find_entry(int data[], int n, int x)
{
int a = (n/2);
int b = n;
int tmp = 0;
while (x != data[a])
{
if (x > data[a])
{
tmp = a;
a = (b+a)/2;
b = b;
}
if (x < data[a])
{
a = tmp;
b = a;
}
}
return a;
}
(in a previous version I was using the floor function to round the numbers contained in a to their integer parts, but I understand this is not necessary.)
I have tested the program for example for the following array in this main:
int main()
{
int n = 6; int x = 12;
int array1[] = {3,12,5,9,7,11};
cout << "The entry " << x << " is found at position "
<< 1+Find_entry(array1, n, x) << endl;
return 0;
}
When I type as in this example x=12, the program gives the correct answer 1. Same thing for x=3, x=11 and x=9. But if I type x=7 or x=5, the program refuses to give an output and I get a message like
"Process terminated with status -1073741510 (0 minute(s), 9 second(s))".
Can anybody explain what's the problem here? How can be the code fixed?? Thank you all for your answers.
You cannot use binary search for unsorted array. Use linear search.
int Find_entry(int data[], int n, int x)
{
int a = 0;
while (a < n && x != data[a]) a++;
return a;
}
Binary search only works on sorted inputs.