Reverse Integer Catch overflow C++ - c++

Hello I am trying a simple reverse integer operation in c++. Code below:
#include <iostream>
#include <algorithm>
#include <climits>
using namespace std;
class RevInteger {
public:
int reverse(int x)
{
int result = 0;
bool isNeg = x > 0 ? false : true;
x = abs(x);
while (x != 0)
{
result = result * 10 + x % 10;
x = x / 10;
}
if (isNeg)
result *= -1;
if (result > INT_MAX || result < INT_MIN)
return 0;
else
return (int)result;
}
};
When I give it an input as 1534236469; I want it to return me 0, instead it returns me some junk values. What is wrong in my program. Also, I am trying to use the climits lib for the purpose, is there a simpler way of doing the same?

The simplest approach is to use long long in place of int for the result, and check for overflow at the end:
long long result = 0;
/* the rest of your code */
return (int)result; // Now the cast is necessary; in your code you could do without it
Another approach is to convert the int to string, reverse it, and then use the standard library to try converting it back, and catch the problems along the way (demo):
int rev(int n) {
auto s = to_string(n);
reverse(s.begin(), s.end());
try {
return stoi(s);
} catch (...) {
return 0;
}
}
If you must stay within integers, an approach would be to check intermediate result before multiplying it by ten, and also checking for overflow after the addition:
while (x != 0) {
if (result > INT_MAX/10) {
return 0;
}
result = result * 10 + x % 10;
if (result < 0) {
return 0;
}
x = x / 10;
}

class Solution {
public:
int reverse(int x) {
int reversed = 0;
while (x != 0) {
if (reversed > INT_MAX / 10 || reversed < INT_MIN / 10) return 0;
reversed = reversed * 10 + (x % 10);
x /= 10;
}
return reversed;
}
};
If reversed bigger than 8 digit INT_MAX (INT_MAX / 10), then if we add 1 digit to reversed, we will have an int overflow. And similar to INT_MIN.

As suggested by #daskblinkenlight; changing the result as long long and type casting at the end solves the problem.
Working class:
class intReverse {
public:
int reverse(int x) {
long long result = 0; // only change here
bool isNeg = x > 0 ? false : true;
x = abs(x);
while (x != 0) {
result = result * 10 + x % 10;
x = x / 10;
}
if (isNeg) {
result *= -1;
}
if (result > INT_MAX || result < INT_MIN)
{
return 0;
}
else
{
return (int) result;
}
}
};

int reverse(int x) {
int pop = 0;
int ans = 0;
while(x) {
// pop
pop = x % 10;
x /= 10;
// check overflow
if(ans > INT_MAX/10 || ans == INT_MAX/10 && pop > 7) return 0;
if(ans < INT_MIN/10 || ans == INT_MIN/10 && pop < -8) return 0;
// push
ans = ans * 10 + pop;
}
return ans;
}

Related

The next prime number

Among the given input of two numbers, check if the second number is exactly the next prime number of the first number. If so return "YES" else "NO".
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int nextPrime(int x){
int y =x;
for(int i=2; i <=sqrt(y); i++){
if(y%i == 0){
y = y+2;
nextPrime(y);
return (y);
}
}
return y;
}
int main()
{
int n,m, x(0);
cin >> n >> m;
x = n+2;
if(n = 2 && m == 3){
cout << "YES\n";
exit(0);
}
nextPrime(x) == m ? cout << "YES\n" : cout << "NO\n";
return 0;
}
Where is my code running wrong? It only returns true if next number is either +2 or +4.
Maybe it has something to do with return statement.
I can tell you two things you are doing wrong:
Enter 2 4 and you will check 4, 6, 8, 10, 12, 14, 16, 18, ... for primality forever.
The other thing is
y = y+2;
nextPrime(y);
return (y);
should just be
return nextPrime(y + 2);
Beyond that your loop is highly inefficient:
for(int i=2; i <=sqrt(y); i++){
Handle even numbers as special case and then use
for(int i=3; i * i <= y; i += 2){
Using a different primality test would also be faster. For example Miller-Rabin primality test:
#include <iostream>
#include <cstdint>
#include <array>
#include <ranges>
#include <cassert>
#include <bitset>
#include <bit>
// square and multiply algorithm for a^d mod n
uint32_t pow_n(uint32_t a, uint32_t d, uint32_t n) {
if (d == 0) __builtin_unreachable();
unsigned shift = std::countl_zero(d) + 1;
uint32_t t = a;
int32_t m = d << shift;
for (unsigned i = 32 - shift; i > 0; --i) {
t = ((uint64_t)t * t) % n;
if (m < 0) t = ((uint64_t)t * a) % n;
m <<= 1;
}
return t;
}
bool test(uint32_t n, unsigned s, uint32_t d, uint32_t a) {
uint32_t x = pow_n(a, d, n);
//std::cout << " x = " << x << std::endl;
if (x == 1 || x == n - 1) return true;
for (unsigned i = 1; i < s; ++i) {
x = ((uint64_t)x * x) % n;
if (x == n - 1) return true;
}
return false;
}
bool is_prime(uint32_t n) {
static const std::array witnesses{2u, 3u, 5u, 7u, 11u};
static const std::array bounds{
2'047u, 1'373'653u, 25'326'001u, 3'215'031'751u, UINT_MAX
};
static_assert(witnesses.size() == bounds.size());
if (n == 2) return true; // 2 is prime
if (n % 2 == 0) return false; // other even numbers are not
if (n <= witnesses.back()) { // I know the first few primes
return (std::ranges::find(witnesses, n) != std::end(witnesses));
}
// write n = 2^s * d + 1 with d odd
unsigned s = 0;
uint32_t d = n - 1;
while (d % 2 == 0) {
++s;
d /= 2;
}
// test widtnesses until the bounds say it's a sure thing
auto it = bounds.cbegin();
for (auto a : witnesses) {
//std::cout << a << " ";
if (!test(n, s, d, a)) return false;
if (n < *it++) return true;
}
return true;
}
And yes, that is an awful lot of code but it runs very few times.
Something to do with the return statement
I would say so
y = y+2;
nextPrime(y);
return (y);
can be replaced with
return nextPrime(y + 2);
Your version calls nextPrime but fails to do anything with the return value, instead it just returns y.
It would be more usual to code the nextPrime function with another loop, instead of writing a recursive function.

Adding negative and positive numbers up to 10^100000

I've been trying to solve this problem (from school) for just about a week now. We're given two numbers, from -(10^100000) to +that.
Of course the simplest solution is to implement written addition, so that's what I did. I decided, that I would store the numbers as strings, using two functions:
int ti(char a) { // changes char to int
int output = a - 48;
return output;
}
char tc(int a) { // changes int to char
char output = a + 48;
return output;
}
This way I can store negative digits, like -2. With that in mind I implemented a toMinus function:
void toMinus(std::string &a) { // 123 -> -1 -2 -3
for (auto &x : a) {
x = tc(-ti(x));
}
}
I also created a changeSize function, which adds 0 to the beginning of the number until they are both their max size + 1 and removeZeros, which removes leading zeros:
void changeSize(std::string &a, std::string &b) {
size_t exp_size = std::max(a.size(), b.size()) + 2;
while (a.size() != exp_size) {
a = '0' + a;
}
while (b.size() != exp_size) {
b = '0' + b;
}
}
void removeZeros(std::string &a) {
int i = 0;
for (; i < a.size(); i++) {
if (a[i] != '0') {
break;
}
}
a.erase(0, i);
if (a.size() == 0) {
a = "0";
}
}
After all that, I created the main add() function:
std::string add(std::string &a, std::string &b) {
bool neg[2] = {false, false};
bool out_negative = false;
if (a[0] == '-') {
neg[0] = true;
a.erase(0, 1);
}
if (b[0] == '-') {
neg[1] = true;
b.erase(0, 1);
}
changeSize(a, b);
if (neg[0] && !(neg[1] && neg[0])) {
toMinus(a);
}
if(neg[1] && !(neg[1] && neg[0])) {
toMinus(b);
}
if (neg[1] && neg[0]) {
out_negative = true;
}
// Addition
for (int i = a.size() - 1; i > 0; i--) {
int _a = ti(a[i]);
int _b = ti(b[i]);
int out = _a + _b;
if (out >= 10) {
a[i - 1] += out / 10;
} else if (out < 0) {
if (abs(out) < 10) {
a[i - 1]--;
} else {
a[i - 1] += abs(out) / 10;
}
if (i != 1)
out += 10;
}
a[i] = tc(abs(out % 10));
}
if (ti(a[0]) == -1) { // Overflow
out_negative = true;
a[0] = '0';
a[1]--;
for (int i = 2; i < a.size(); i++) {
if (i == a.size() - 1) {
a[i] = tc(10 - ti(a[i]));
} else {
a[i] = tc(9 - ti(a[i]));
}
}
}
if (neg[0] && neg[1]) {
out_negative = true;
}
removeZeros(a);
if (out_negative) {
a = '-' + a;
}
return a;
}
This program works in most cases, although our school checker found that it doesn't - like instead of
-4400547114413430129608370706728634555709161366260921095898099024156859909714382493551072616612065064
it returned
-4400547114413430129608370706728634555709161366260921095698099024156859909714382493551072616612065064
I can't find what the problem is. Please help and thank you in advance.
Full code on pastebin
While I think your overall approach is totally reasonable for this problem, your implementation seems a bit too complicated. Trying to solve this myself, I came up with this:
#include <iostream>
#include <limits>
#include <random>
#include <string>
bool greater(const std::string& a, const std::string& b)
{
if (a.length() == b.length()) return a > b;
return a.length() > b.length();
}
std::string add(std::string a, std::string b)
{
std::string out;
bool aNeg = a[0] == '-';
if (aNeg) a.erase(0, 1);
bool bNeg = b[0] == '-';
if (bNeg) b.erase(0, 1);
bool resNeg = aNeg && bNeg;
if (aNeg ^ bNeg && (aNeg && greater(a, b) || bNeg && greater(b, a)))
{
resNeg = true;
std::swap(a, b);
}
int i = a.length() - 1;
int j = b.length() - 1;
int carry = 0;
while (i >= 0 || j >= 0)
{
const int digitA = (i >= 0) ? a[i] - '0' : 0;
const int digitB = (j >= 0) ? b[j] - '0' : 0;
const int sum = (aNeg == bNeg ? digitA + digitB : (bNeg ? digitA - digitB : digitB - digitA)) + carry;
carry = 0;
if (sum >= 10) carry = 1;
else if (sum < 0) carry = -1;
out = std::to_string((sum + 20) % 10) + out;
i--;
j--;
}
if (carry) out = '1' + out;
while (out[0] == '0') out.erase(0, 1);
if (resNeg) out = '-' + out;
return out;
}
void test()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(-std::numeric_limits<int32_t>::max(), std::numeric_limits<int32_t>::max());
for (int i = 0; i < 1000000; ++i)
{
const int64_t a = dis(gen);
const int64_t b = dis(gen);
const auto expected = std::to_string(a + b);
const auto actual = add(std::to_string(a), std::to_string(b));
if (actual != expected) {
std::cout << "mismatch expected: " << expected << std::endl;
std::cout << "mismatch actual : " << actual << std::endl;
std::cout << " a: " << a << std::endl;
std::cout << " b: " << b << std::endl;
}
}
}
int main()
{
test();
}
It can potentially be further optimized, but the main points are:
If the sign of both numbers is the same, we can do simple written addition. If both are negative, we simply prepend - at the end.
If the signs are different, we do written subtraction. If the minuend is greater than the subtrahend, there's no issue, we know that the result will be positive. If, however, the subtrahend is greater, we have to reformulate the problem. For example, 123 - 234 we would formulate as -(234 - 123). The inner part we can solve using regular written subtraction, after which we prepend -.
I test this with random numbers for which we can calculate the correct result using regular integer arithmetic. Since it doesn't fail for those, I'm pretty confident it also works correctly for larger inputs. An approach like this could also help you uncover cases where your implementation fails.
Other than that, I think you should use a known failing case with a debugger or simply print statements for the intermediate steps to see where it fails. The only small differences in the failing example you posted could point at some issue with handling a carry-over.

Prime factorisation in C++ using Fermat's Method

I am currently working on a program in C++, the ultimate goal of which is to display a list of prime factors for a given value, up to the limit of unsigned long int.
It takes advantage of trial division for the first 1000 prime numbers, and uses Fermat's Method of Factorisation for every value thereafter.
Generally, I'd say the program works okay for most numbers I've tested it with, including some larger numbers. However, I seem to have hit a snag with certain numbers. For example, when the prime number 18446744073709551557 is entered, it crashes entirely. For other larger values such as 246819835539726757, it displays the first five prime factors (7, 11, 37, 131, and 557) correctly, but miscalculates the last two, which should be 18379 and 64601.
The code for the function is as follows:
std::list < unsigned long int >primeFactors(unsigned long int n)
{
bool complete = false;
std::list<unsigned long int> factors;
unsigned long int ans1 = 0;
unsigned long int ans2 = 0;
int a;
int b;
// If n is 0 or 1, return a blank list
//
// This is run outside the while loop, as n will never be 0 or 1 after
// the initial calculation
if (n == 0 || n == 1)
{
complete = true;
return factors;
}
while (complete == false)
{
// if n is a prime number, add to the list and return
if (isPrime(n) == true)
{
factors.push_back(n);
complete = true;
return factors;
}
// if n is even (i.e. divisible by 2), add 2 and n/2 to the list and
// return
else if (divisibleByPrime(n) != 0)
{
unsigned long int divisor = divisibleByPrime(n);
ans1 = divisor;
ans2 = n / divisor;
if (isPrime(ans1) == true && isPrime(ans2) == true)
{
factors.push_back(ans1);
factors.push_back(ans2);
complete = true;
return factors;
}
else
{
if (isPrime(ans1) == true)
{
factors.push_back(ans1);
n = ans2;
}
else
{
factors.push_back(ans2);
n = ans1;
}
}
}
else
{
// a is the square root of n + a^2
unsigned long int i = 1;
float squareRoot;
std::stringstream ss;
std::string str;
bool isDouble = true;
bool answerFound = false;
unsigned long int x;
unsigned long int y;
while (answerFound == false)
{
isDouble = false;
squareRoot = (float)sqrt(n + (i * i));
ss << squareRoot;
str = ss.str();
for (char& i : str)
{
if (strchr(".", i) != NULL)
{
isDouble = true;
}
}
if (isDouble == true)
{
ss.str("");
i += 1;
}
else
{
answerFound = true;
}
}
x = (unsigned long int) squareRoot;
y = i;
ans1 = x + y;
ans2 = x - y;
if (isPrime(ans1) == true && isPrime(ans2) == true)
{
factors.push_back(ans1);
factors.push_back(ans2);
complete = true;
return factors;
}
else
{
if (isPrime(ans1))
{
factors.push_back(ans1);
n = ans2;
}
else
{
factors.push_back(ans2);
n = ans1;
}
}
}
}
I have not included functions such as isPrime or divisibleByPrime as both seem to work fine in an isolated environment.
EDIT: I appreciate certain variables are such are a little messy at the minute, but I plan on rectifying that soon.

How to I reduce a chain of if statements?

How to I reduce a chain of if statements in C++?
if(x == 3) {
a = 9876543;
}
if(x == 4) {
a = 987654;
}
if(x == 5) {
a = 98765;
}
if(x == 6) {
a = 9876;
}
if(x == 7) {
a = 987;
}
if(x == 8) {
a = 98;
}
if(x == 9) {
a = 9;
}
This is the example code.
You can generate this value mathematically, by using integer division:
long long orig = 9876543000;
long long a = orig / ((long) pow (10, x));
EDIT:
As #LogicStuff noted in the comments, it would be much more elegant to subtract 3 from x, instead of just multiplying orig by another 1000:
long orig = 9876543;
long a = orig / ((long) pow (10, x - 3));
With an array, you may do:
if (3 <= x && x <= 9) {
const int v[] = {9876543, 987654, 98765, 9876, 987, 98, 9};
a = v[x - 3];
}
Something like:
#include <iostream>
#include <string>
int main() {
int x = 4;
int a = 0;
std::string total;
for(int i = 9; i > 0 ; --i)
{
if(x <= i)
total += std::to_string(i);
}
a = std::stoi(total, nullptr);
std::cout << a << std::endl;
return 0;
}
http://ideone.com/2Cdve1
If the data can be derived, I'd recommend using one of the other answers.
If you realize their are some edge cases that end up making the derivation more complicated, consider a simple look-up table.
#include <iostream>
#include <unordered_map>
static const std::unordered_multimap<int,int> TABLE
{{3,9876543}
,{4,987654}
,{5,98765}
,{6,9876}
,{7,987}
,{8,98}
,{9,9}};
int XtoA(int x){
int a{0};
auto found = TABLE.find(x);
if (found != TABLE.end()){
a = found->second;
}
return a;
}
int main(){
std::cout << XtoA(6) << '\n'; //prints: 9876
}

Checking if a number is a palindrome

I've tried to check whether a number is a palindrome with the following code:
unsigned short digitsof (unsigned int x)
{
unsigned short n = 0;
while (x)
{
x /= 10;
n++;
}
return n;
}
bool ispalindrome (unsigned int x)
{
unsigned short digits = digitsof (x);
for (unsigned short i = 1; i <= digits / 2; i++)
{
if (x % (unsigned int)pow (10, i) != x % (unsigned int)pow (10, digits - 1 + i))
{
return false;
}
}
return true;
}
However, the following code isn't able to check for palindromes - false is always returned even if the number is a palindrome.
Can anyone point out the error?
(Please note: I'm not interested to make it into a string and reverse it to see where the problem is: rather, I'm interested to know where the error is in the above code.)
I personally would just build a string from the number, and then treat it as a normal palindrome check (check that each character in the first half matches the ones at length()-index).
x % (unsigned int)pow (10, i) is not the ith digit.
The problem is this:
x % (unsigned int)pow (10, i)
Lets try:
x =504405
i =3
SO I want 4.
x % 10^3 => 504405 %1000 => 405 NOT 4
How about
x / (unsigned int)pow (10, i -1) % 10
Just for more info! The following two functions are working for me:
double digitsof (double x)
{
double n = 0;
while (x > 1)
{
x /= 10;
n++;
}
return n;
}
bool ispalindrome (double x)
{
double digits = digitsof (x);
double temp = x;
for(double i = 1; i <= digits/2; i++)
{
float y = (int)temp % 10;
cout<<y<<endl;
temp = temp/10;
float z = (int)x / (int)pow(10 , digits - i);
cout<<(int)z<<endl;
x = (int)x % (int)pow(10 , digits - i);
if(y != z)
return false;
}
return true;
}
Code to check if given number is palindrome or not in JAVA
import java.util.*;
public class HelloWorld{
private static int countDigits(int num) {
int count = 0;
while(num>0) {
count++;
num /= 10;
}
return count;
}
public static boolean isPalin(int num) {
int digs = HelloWorld.countDigits(num);
int divderToFindMSD = 1;
int divderToFindLSD = 1;
for (int i = 0; i< digs -1; i++)
divderToFindMSD *= 10;
int mid = digs/2;
while(mid-- != 0)
{
int msd = (num/divderToFindMSD)%10;
int lsd = (num/divderToFindLSD)%10;
if(msd!=lsd)
return false;
divderToFindMSD /= 10;
divderToFindLSD *= 10;
}
return true;
}
public static void main(String []args) {
boolean isPalin = HelloWorld.isPalin(1221);
System.out.println("Results: " + isPalin);
}
}
I have done this with my own solution which is restricted with these conditions
Do not convert int to string.
Do not use any helper function.
var inputNumber = 10801
var firstDigit = 0
var lastDigit = 0
var quotient = inputNumber
while inputNumber > 0 {
lastDigit = inputNumber % 10
var tempNum = inputNumber
var count = 0
while tempNum > 0 {
tempNum = tempNum / 10
count = count + 1
}
var n = 1
for _ in 1 ..< count {
n = n * 10
}
firstDigit = quotient / n
if firstDigit != lastDigit {
print("Not a palindrome :( ")
break
}
quotient = quotient % n
inputNumber = inputNumber / 10
}
if firstDigit == lastDigit {
print("It's a palindrome :D :D ")
}