C++ problems with division [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I need to make a program in C++ in which I insert a number 'n' that's with 4 digits and it's a simple number, in the console and the console is showing me the multiplication of the certain number with 4 digits which I first needed to write.
I tried to write (n/!2) in order to make the program execute only if the number can't divide by 2 and the console showed "main.cpp:22:36: warning: division by zero [-Wdiv-by-zero]".
I've tried removing
(n /! 2) and the code got executed without a problem. I will be glad if someone can tell me how can I fix it.
#include <bits/stdc++.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int getProduct(int n)
{
int product = 1;
while (n != 0) {
product = product * (n % 10);
n = n / 10;
}
return product;
}
int main()
{
int n;
cout << "insert n ";
cin >> n;
if (n >= 1000 && n <= 9999 && n /! 2) {
cout << (getProduct(n));
}
}

In the calculation n / !2 You effectively do n / 0.
! is short for not, not 2 is a boolean expression where 2 (anything but 0) is true.
not true is false.
false is promoted to an int in the calculation and false there becomes 0.
Solution: Use n % 2 != 0 or n & 1 to check for odd numbers.

You are looking for modulo operation. Modulo (the remainder from division) is equal to zero if number is divisible by the other one and non-zero otherwise.
if (n >=1000 && n <= 9999 && (n % 2) != 0)

tried to write (n/!2) in order to make the program execute only if the number can't divide by 2
n / !2
This evaluates to n / 0. which triggers your warning.
To check if n is odd, you should do this instead:
n % 2 != 0

! operator have higher precedence than / , So your expression becomes
=> n/(!2)
=> n/0
Instead you shoud use (n%2==0) to check for even number.

Related

Music Chairs problem implementation in C++

I am currently practicing algorithms and DS. I have stumbled upon a question that I can't figure out how to solve. So the question's link is there:
In summary, it says that there is a number of chairs in a circle, and the position of the person (relative to a certain chair), and how many M movements he should make.
So the input is as following:
3 integer numbers N, M, X , The number of chairs, the number of times the boy should move and the first chair he will start from respectively ( 1  ≤  X  ≤  N < 2^63 , 0  ≤  M < 2^63 )
So, what have I done so far? I thought about the following:
So I thought that the relative position after M movements is (x+m) % n, and since this can cause Integer overflow, I have done it like that, ((x%n) + (m%n)) % n. I have figured out that if the person has reached the last index of chair, it will be 0 so I handled that. However, it passes only 2 tests. I don't need any code to be written, I want to directed in the right way of thinking. Here is my code so far:
#include <iostream>
using namespace std;
int main() {
long long n, m, x;
cin >> n >> m >> x;
// After each move, he reaches (X+1).
// X, N chairs.
// ((X % N) + (M % N)) % N;
// Odd conideration.
if ( m % 2 == 1) {
m += 1;
}
long long position = (x % n + m % n) % n;
if (position == 0) {
position = n;
}
cout << position;
return 0;
}
If the question required specific error handling, it should have stated so (so don't feel bad).
In every real-world project, there should be a standard to dictate what to do with weird input. Do you throw? Do you output a warning? If so, does it have to be translated to the system language?
In the absence of such instructions I would err toward excluding these values after reading them. Print an error to std::cerr (or throw an exception). Do this as close to where you read them as possible.
For overflow detection, you can use the methods described here. Some may disagree, and for a lab-exercise, it's probably not important. However, there is a saying in computing "Garbage in == Garbage out". It's a good habit to check for garbage before processing, rather than attempting to "recycle" garbage as you process.
Here's the problem:
Say the value of N is 2^63-1, and X and M are both 2^63 - 2.
When your program runs untill the ((X % N) + (M % N)) % N part,
X % N evaluates into 2^63 - 2 (not changed), and so does M % N.
Then, the addition between the two results occurs, 2^63 - 2 + 2^63 - 2 there is the overflow happening.
After the comment of #WBuck, the answer is actually rather easy which is to change the long long to unsigned because there are no negative numbers and therefore, increase the MAX VALUE of long long (when using unsigned).
Thank you so much.

when this code executes, it shows no output. Why is that? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Following code has no output when it executes. Can anyone explain the following code?
int main() {
int i, j;
for (i = 0; i < 10; i++) {
if (i % 2)
printf("%d\t", i);
else
break;
}
}
0 % 2 gives false so the loop terminates at the first iteration without calling the printf.
Your code has two issues:
1.
if (i % 2)
The condition of (i % 2) evaluates to false because the calculation - 0 divided by 2 - result in 0 -> 0 / 2 = 0. The remainder is also 0.
2.
else break;
That provides the result if (i % 2) is not true (which is the case with 0 at the first iteration) you immediately will break out of the for loop. Omit the break; statement in general, if you want to proof if all values from 0 to 9 have an remainder when divided by 2 or not.
Note that to pack break; in an separate else statement is nonetheless redundant.
Side note:
j has no use in your code.
I guess what you want is something like that:
#include <stdio.h>
int main (void) {
int i, j;
for ( i = 0; i < 10; i++ ) {
if ( ( j = i % 2 ) )
printf("(%d / 2) has a remainder of %d.\n", i, j);
else
printf("(%d / 2) has no remainder.\n", i);
}
}
Output:
(0 / 2) has no remainder.
(1 / 2) has a remainder of 1.
(2 / 2) has no remainder.
(3 / 2) has a remainder of 1.
(4 / 2) has no remainder.
(5 / 2) has a remainder of 1.
(6 / 2) has no remainder.
(7 / 2) has a remainder of 1.
(8 / 2) has no remainder.
(9 / 2) has a remainder of 1.
Try this code online.
Note that by the division 1 / 2, the result 0.5 is raised to the nearest upper integral value 1 because of the implicit double to int conversion.
i % 2 gives the remainder of the Euclidian division of i by 2. It does NOT mean "i is divisible by 2". If the latter is true, then i % 2 gives 0 which implicitely converts to false. If it is false, then i % 2 gives 1 which implicitely converts to true. Therefore, in the first iteration, the conditional ex^pression evaluates to false so you break out of the loop immediately.
If you want to check the divisibility of i by 2, you must use i % 2 == 0.

pigeon hole / multiple numbers

input : integer ( i'll call it N ) and (1 <= N <= 5,000,000 )
output : integer, multiple of N and only contains 0,7
Ex.
Q1 input : 1 -> output : 7 ( 7 mod 1 == 0 )
Q2 input : 2 -> output : 70 ( 70 mod 2 == 0 )
#include <string>
#include <iostream>
using namespace std;
typedef long long ll;
int remaind(string num, ll m)
{
ll mod = 0;
for (int i = 0; i < num.size(); i++) {
int digit = num[i] - '0';
mod = mod * 10 + digit;
mod = mod % m;
}
return mod;
}
int main()
{
int n;
string ans;
cin >> n;
ans.append(n, '7');
for (int i = ans.length() - 1; i >= 0; i--)
{
if (remaind(ans, n) == 0)
{
cout << ans;
return 0;
}
ans.at(i) = '0';
}
return 0;
}
is there a way to lessen the time complexity?
i just tried very hard and it takes little bit more time to run while n is more than 1000000
ps. changed code
ps2. changed code again because of wrong code
ps3. optimize code again
ps4. rewrite post
Your approach is wrong, let's say you divide "70" by 5. Then you result will be 2 which is not right (just analyze your code to see why that happens).
You can really base your search upon numbers like 77777770000000, but think more about that - which numbers you need to add zeros and which numbers you do not.
Next, do not use strings! Think of reminder for a * b if you know reminder of a and reminder of b. When you program it, be careful with integer size, use 64 bit integers.
Now, what about a + b?
Finally, find reminders for numbers 10, 100, 1000, 10000, etc (once again, do not use strings and still try to find reminder for any power of 10).
Well, if you do all that, you'll be able to easily solve the whole problem.
May I recommend any of the boost::bignum integer classes?
I suspect uint1024_t (or whatever... they also have 128, 256, and 512, bit ints already typedefed, and you can declare your own easily enough) will meet your needs, allowing you to perform a single %, rather than one per iteration. This may outweigh the performance lost when using bignum vs c++'s built-in ints.
2^1024 ~= 1.8e+308. Enough to represent any 308 digit number. That's probably excessive.
2^512 ~= 1.34e+154. Good for any 154 digit number.
etc.
I suspect you should first write a loop that went through n = 4e+6 -> 5e+6 and wrote out which string got the longest, then size your uint*_t appropriately. If that longest string length is more than 308 characters, you could just whip up your own:
typedef number<cpp_int_backend<LENGTH, LENGTH, unsigned_magnitude, unchecked, void> > myReallyUnsignedBigInt;
The modulo operator is probably the most expensive operation in that inner loop. Performing once per iteration on the outer loop rather than at the inner loop (O(n) vs O(n^2)) should save you quite a bit of time.
Will that plus the whole "not going to and from strings" thing pay for bignum's overhead? You'll have to try it and see.

How does the modulus operator work?

Let's say that I need to format the output of an array to display a fixed number of elements per line. How do I go about doing that using modulus operation?
Using C++, the code below works for displaying 6 elements per line but I have no idea how and why it works?
for ( count = 0 ; count < size ; count++)
{
cout << somearray[count];
if( count % 6 == 5) cout << endl;
}
What if I want to display 5 elements per line? How do i find the exact expression needed?
in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:
5 % 2 = 1
13 % 5 = 3
With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).
To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).
Basically modulus Operator gives you remainder
simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2
for same thing C++ has modulus operator ('%')
Basic code for explanation
#include <iostream>
using namespace std;
int main()
{
int num = 11;
cout << "remainder is " << (num % 3) << endl;
return 0;
}
Which will display
remainder is 2
It gives you the remainder of a division.
int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c
This JSFiddle project could help you to understand how modulus work:
http://jsfiddle.net/elazar170/7hhnagrj
The modulus function works something like this:
function modulus(x,y){
var m = Math.floor(x / y);
var r = m * y;
return x - r;
}
You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use
if (count % 5 == 4)

C++ reading a sequence of integers

gooday programers. I have to design a C++ program that reads a sequence of positive integer values that ends with zero and find the length of the longest increasing subsequence in the given sequence. For example, for the following
sequence of integer numbers:
1 2 3 4 5 2 3 4 1 2 5 6 8 9 1 2 3 0
the program should return 6
i have written my code which seems correct but for some reason is always returning zero, could someone please help me with this problem.
Here is my code:
#include <iostream>
using namespace std;
int main()
{
int x = 1; // note x is initialised as one so it can enter the while loop
int y = 0;
int n = 0;
while (x != 0) // users can enter a zero at end of input to say they have entered all their numbers
{
cout << "Enter sequence of numbers(0 to end): ";
cin >> x;
if (x == (y + 1)) // <<<<< i think for some reason this if statement if never happening
{
n = n + 1;
y = x;
}
else
{
n = 0;
}
}
cout << "longest sequence is: " << n << endl;
return 0;
}
In your program, you have made some assumptions, you need to validate them first.
That the subsequence always starts at 1
That the subsequence always increments by 1
If those are correct assumptions, then here are some tweaks
Move the cout outside of the loop
The canonical way in C++ of testing whether an input operation from a stream has worked, is simply test the stream in operation, i.e. if (cin >> x) {...}
Given the above, you can re-write your while loop to read in x and test that x != 0
If both above conditions hold, enter the loop
Now given the above assumptions, your first check is correct, however in the event the check fails, remember that the new subsequence starts at the current input number (value x), so there is no sense is setting n to 0.
Either way, y must always be current value of x.
If you make the above logic changes to your code, it should work.
In the last loop, your n=0 is execute before x != 0 is check, so it'll always return n = 0. This should work.
if(x == 0) {
break;
} else if (x > y ) {
...
} else {
...
}
You also need to reset your y variable when you come to the end of a sequence.
If you just want a list of increasing numbers, then your "if" condition is only testing that x is equal to one more than y. Change the condition to:
if (x > y) {
and you should have more luck.
You always return 0, because the last number that you read and process is 0 and, of course, never make x == (y + 1) comes true, so the last statement that its always executed before exiting the loop its n=0
Hope helps!
this is wrong logically:
if (x == (y + 1)) // <<<<< i think for some reason this if statement if never happening
{
Should be
if(x >= (y+1))
{
I think that there are more than one problem, the first and most important that you might have not understood the problem correctly. By the common definition of longest increasing subsequence, the result to that input would not be 6 but rather 8.
The problem is much more complex than the simple loop you are trying to implement and it is usually tackled with Dynamic Programming techniques.
On your particular code, you are trying to count in the if the length of the sequence for which each element is exactly the successor of the last read element. But if the next element is not in the sequence you reset the length to 0 (else { n = 0; }), which is what is giving your result. You should be keeping a max value that never gets reset back to 0, something like adding in the if block: max = std::max( max, n ); (or in pure C: max = (n > max? n : max );. Then the result will be that max value.