code for reversing an integer in cpp using operators - c++

the code is for reversing the input decimal whether negative or positive .if the value of decimal exceeds as max size of int in 32 bit system then return 0.why my code is not working...help me finding the bug .i have attached the code.
#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
float reverseint(int x)
{
int digit[10];
int i = 0;
float revnum = 0;
//store digits of number x
while (x != 0)
{
digit[i] = x % 10;
x = x / 10;
i++;
}
i--;
//reversing number x
while (i >= 0)
{
int j = 0;
revnum = (digit[i] * pow(10, j)) + revnum;
j++;
i--;
}
return revnum;
}
int main()
{
int n;
cin >> n;
if (n < 0)
{
if (n < -pow(2, 31))
cout << 0 << endl;
cout << -reverseint(-n);
}
if (n > 0)
{
if (n > (pow(2, 31) - 1))
cout << 0 << endl;
cout << (reverseint(n)) << endl;
}
return 0;
}

You are initializing j variable on every while loop on reverseint function.
float reverseint(int x)
{
int digit[10];
int i = 0;
float revnum = 0;
//store digits of number x
while (x != 0)
{
digit[i] = x % 10;
x = x / 10;
i++;
}
i--;
//reversing number x
int j = 0; /// Correct place.
while (i >= 0)
{
//int j = 0; /// Wrong. j will be always 0 on every loop. revnum will be sum of digits on variable x.
revnum = (digit[i] * pow(10, j)) + revnum;
j++;
i--;
}
return revnum;
}

Related

Listing down permutations of digit in integer form in C++ using 2 for loops, by only switching 2 digits

I need to make a code to switch 2 digits in a number and make it into a new integer
For example
12-->21
123 becomes
213(1,2 switch)
312(1,3 switch)
132 (2,3 switch)
for up to 8 digits of numbers
this is what I came up so far
#include <iostream>
#include <iomanip>
using namespace std;
int digitcount(int n) {
int count=0;
if (n == 0)
return 1;
while (n != 0) {
n = n / 10;
count++;
}
return count;
}
int pow(int num,int n) {
int x = 1;
if (n == 0) {
return 1;
}
for (int i = 0; i < n; i++) {
x = x * num;
}
return x;
}
int a[8];
int main() {
int input;
int newnum = 0;
cout << "Input an integer: ";
cin >> input;
int b = input;
int digit = digitcount(input);
for (int i = digit-1; i>=0; i--) {
a[i] = b % 10;
b = b / 10;
}
for (int i = 0; i < digit - 1; i++) {
newnum = 0;
for (int j = i+1; j < digit; j++) {
if (a[j] == a[i]) {
continue;
}
newnum = a[i] * pow(10, digit - j - 1) + a[i] * pow(10, digit);
}
}
}

Why is this code not printing the prime factors of num?

I wrote this code for obtaining the prime factors of a number taken as an input from the user.
#include<bits/stdc++.h>
using namespace std;
void prime_Factors(int);
bool isPrime(int);
int main()
{
int num;
cout << "Enter the number to find it's prime factors: ";
cin >> num;
prime_Factors(num);
}
void prime_Factors(int n1)
{
for(int i = 2; i<n1; i++)
{
if(isPrime(i))
{
int x = i;
while(n1%x==0)
{
cout << i << " ";
x *= i;
}
}
}
}
bool isPrime(int n0)
{
if(n0==1)
return false;
for(int i = 0; i*i <= n0; i++)
{
if(n0%i==0)
return false;
}
return true;
}
The prime_Factors() function call in main() function is not printing the prime factors. Pls help!!
The ranges of the loops are wrong.
Firstly, the loop for(int i = 2; i<n1; i++) will fail to find prime factors of prime numbers (the numbers theirself). It should be for(int i = 2; i<=n1; i++).
Secondly, the loop for(int i = 0; i*i <= n0; i++) will result in division-by-zero. It should be for(int i = 2; i*i <= n0; i++).
Thinking about using the Sieve of Eratosthenes made me try it out:
#include <iostream>
#include <cstdint>
#include <vector>
void prime_factors(uint32_t n) {
while(n % 2 == 0) {
std::cout << "2 ";
n /= 2;
}
std::vector<bool> sieve(n / 2, true);
for (uint32_t i = 3; i * i <= n; i += 2) {
if (sieve.at(i / 2 - 1)) {
uint32_t j = i * i;
for (; j < n; j += 2 * i) {
sieve.at(j / 2 - 1) = false;
}
if (j == n) {
do {
std::cout << i << " ";
n /= i;
} while (!sieve.at(n / 2 - 1));
}
}
}
if (n > 1) std::cout << n;
std::cout << "\n";
}
int main() {
prime_factors(123456789);
}
https://godbolt.org/z/8doWbYrs6

I cannot seem to find the problem Exception thrown: write access violation. prime was 0x828753A3. C++

I'm currently coding the sieve of Atkin in C++ and it is working well when I'm generating all prime numbers under 50 000 or so but when I try with 50 000 or more the error "Exception thrown: write access violation. prime was 0x828753A3." appears and I can't seem to understand why.
this error appears under the bloc of code where I get rid of multiple of k^2
//get rid of multiple of prime k^2
//start at 5 to skip useless loop with 2 and 3
for (int i = 5; i < n + 1; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i * i) {
prime[j] = false; //Exception thrown: write access violation. prime was 0x828753A3
}
}
}
Here is the full code:
#include <iostream>
using namespace std;
void Atkins(int n) {
bool* prime = new bool[n + 1];
int nbr = 0;
// set all value to false
for (int i = 0; i < n + 1; i++) {
prime[i] = false;
}
//test for all x y combination
for (int x = 1; x*x < n; x++){
for (int y = 1; y * y < n; y++) {
//test three different algorithm possible
int k = 4 * x * x + y * y;
if (k <= n && (k % 12 == 1 || k % 12 == 5)) {
prime[k] = !prime[k];
}
k = 3 * x * x + y * y;
if (k <= n && k % 12 == 7) {
prime[k] = !prime[k];
}
if (x > y) {
k = 3 * x * x - y * y;
if (k <= n && k % 12 == 11) {
prime[k] = !prime[k];
}
}
}
}
//get rid of multiple of prime k^2
//start at 5 to skip useless loop with 2 and 3
for (int i = 5; i < n + 1; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i * i) {
prime[j] = false; //Exception thrown: write access violation. prime was 0x828753A3
}
}
}
//base prime number in list
if (n >= 2) {
cout << "2\n";
nbr++;
}
if (n >= 3) {
cout << "3\n";
nbr++;
}
//print all prime number in list
for (int i = 5; i < n + 1; i++) {
if (prime[i]) {
nbr++;
cout << i << "\n";
}
}
cout << "Il y a " << nbr << " nombre premier entre 0 et " << n << "\n";
delete[] prime;
system("PAUSE");
}
int main() {
Atkins(50000);
return 0;
}
While you're properly guarded all accesses against too big index values, you didn't expect them to be negative.
By running the code under debugger you can see that when error happens, n = -2146737495.
Such value was cause by "integer overflow". When i=46349 -> i*i= 2148229801, which is more than int (32 bit) can take (2^31 - 1).
Simple way is to use long long int data type for multiplication (it has 64 bits, so max value is 2^63 - 1).
int j = i * i; j <= n; j += i * i -> long long int j = (long long int)i * i; j <= n; j += (long long int)i * i.
Several things you need to realize:
On a 32bit platform, INT_MAX is 2147483647. The maximum natural root below that value is 46340 (e.g. root of x^2 = 2147395600.
Automatic representation promotion isn't a language feature. I.e. if you have two int values x=50000 and y=50000, the expression x*y is still int, but because of signed integer overflow, has platform-dependent results. You don't want that.
Yes, you can change the data types to larger 64bit representations, but you don't have to do that. To accommodate the above problem and considerably reduce your workload, understand that you should limit your loops without having to compute i * i or j * j as part of the conditionals. Rather, you can cap the top-end of those loops (and more) using the real thing you're trying to prevent: cross over the square root boundary of n.
For example:
for (int x = 1; x*x < n; x++){
Suppose there was a value nr that was the result of acquiring the integer portion of the square root of n. Then, would what you're really trying to do be better considered as:
int nr = sqrt(n) + 1;
for (int x=1; x < nr; ++x)
So lets do that.
#include <iostream>
#include <cmath>
using namespace std;
void Atkins(int n)
{
bool *prime = new bool[n + 1];
int nbr = 0;
// set all value to false
for (int i = 0; i < n + 1; i++)
{
prime[i] = false;
}
int nr = sqrt(static_cast<double>(n)) + 1;
//test for all x y combination
for (int x = 1; x < nr; x++)
{
for (int y = 1; y < nr; y++)
{
//test three different algorithm possible
int k = 4 * x * x + y * y;
if (k <= n && (k % 12 == 1 || k % 12 == 5))
{
prime[k] = !prime[k];
}
k = 3 * x * x + y * y;
if (k <= n && k % 12 == 7)
{
prime[k] = !prime[k];
}
if (x > y)
{
k = 3 * x * x - y * y;
if (k <= n && k % 12 == 11)
{
prime[k] = !prime[k];
}
}
}
}
//get rid of multiple of prime k^2
//start at 5 to skip useless loop with 2 and 3
for (int i = 5; i < nr; i++)
{
if (prime[i])
{
for (int j = i * i; j <= n; j += i)
{
prime[j] = false; //Exception thrown: write access violation.
}
}
}
//base prime number in list
if (n >= 2)
{
cout << "2\n";
nbr++;
}
if (n >= 3)
{
cout << "3\n";
nbr++;
}
//print all prime number in list
for (int i = 5; i < n + 1; i++)
{
if (prime[i])
{
nbr++;
cout << i << "\n";
}
}
cout << "Il y a " << nbr << " nombre premier entre 0 et " << n << "\n";
delete[] prime;
}
Executing the above version of that function should deliver the results you seek.
See it live here

prime seive algorithm giving a runtime error

I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}

Improve on binary converting algorithm (include negative numbers)

I'm doing some C++ array homework. The goals is to convert decimal to binary (include negative numbers). Here's my code, it gets the job done, but I would like to see if anything can be improved, or any better algorithm (using binary shift maybe?).
#include <iostream>
using namespace std;
// doi tu thap phan sang nhi phan
void decToBinary(int n, int nhiphan[])
{
for (int i=0; i < 16; i++)
{
// to binary
nhiphan[i] = n % 2;
n = n / 2;
}
// inverse array
for (int i = 0, j = 15; i < j; i++, j--)
{
int temp = nhiphan[i];
nhiphan[i] = nhiphan[j];
nhiphan[j] = temp;
}
}
void reverse(int& a)
{
if (a == 0)
a++;
else a--;
}
void outArr(const int a[], int size) {
for (int i = 0; i < size; ++i)
cout << a[i];
}
int main()
{
int nhiphan[16];
int n;
do {
cout << "Nhap so (-255 <= n <= 255) chuyen doi sang nhi phan (16 bit): ";
cin >> n;
} while (n > 255 || n < -255);
if (n < 0) {//check negative
n *= -1;
decToBinary(n, nhiphan);
for (int i = 0; i < 16; i++)// 1's complement
reverse(nhiphan[i]);
// +1
if (nhiphan[15] == 0)//2's complement
nhiphan[15] = 1;
else
{
nhiphan[15] = 0;
int i = 15;
do {
reverse(nhiphan[i-1]);
i--;
} while (nhiphan[i-1] == 0);
}
}
else decToBinary(n, nhiphan);
outArr(nhiphan, 16);
return 0;
}