Improve on binary converting algorithm (include negative numbers) - c++

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;
}

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);
}
}
}

how to find the biggest multiplication between numbers in a given array(limit is 100000 numbers)

I am trying to learn programming and in our school we have exercises which are automatically checked by a bot. The time limit is 1 second and the memory limit is 1024 mb.
I've tried sorting the array in an ascending order and then multiplicating the 2 highest numbers but that was too slow(my sorting algorithm could be slow so if possible suggest a sorting algorithm.)
This is the fastest way that I've been able to do:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int Maksimumas(int n, int X[]);
ofstream fr("U1rez.txt");
ifstream fd("U1.txt");
int main()
{
int n, A[100000], B[100000], maxi=0;
fd >> n;
for (int i = 0; i < n; i++) {
fd >> A[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
B[j] = A[i] * A[j];
}
maxi = Maksimumas(n, B);
A[i] = B[maxi];
}
maxi = Maksimumas(n, A);
fr << A[maxi];
fr.close();
return 0;
}
int Maksimumas(int n, int X[])
{
int maxi = 0;
for (int i = 0; i < n; i++) {
if (X[maxi] < X[i]) {
maxi = i;
}
}
return maxi;
}
n is the size of the array for anyone wondering.
You don't need to sort the entire array - you just need the two largest positive numbers and the two smallest negative numbers. Everything in between is inconsequential.
Instead, you can go over all the input and keep track of the two largest positive numbers and two smallest negative numbers.; At the end of the iteration, multiply each pair (if found), and compare the results.
// fd is opened like the original question, n is the number of elements to read
// that part is omitted for brevity
int max = -1;
int preMax = -1;
int min = 1;
int preMin = 1;
int temp;
for (int i = 0; i < n; i++) {
fd >> temp;
if (temp > preMax) {
if (temp > max) {
preMax = max;
max = temp;
} else {
preMax = temp;
}
} else if (temp < preMin) {
if (temp < min) {
preMin = min;
min = temp;
} else {
preMin = temp;
}
}
}
int result = -1;
if (preMax >= 0) {
result = preMax * max;
}
if (preMin <= 0) {
int tempResult = preMin * min;
if (tempResult > result) {
result = tempResult;
}
}
return result;

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;
}

Can't pass the test (Kadane's algorithm)

I have to find the maximum sum within a one-dimensional array (1 <= N <= 500000) of integers (|a| <= 4000).
If there are multiple subarrays with the same maximum sum, I have to print the shortest one. If there are multiple shortest subarrays, I have to print the leftmost one.
The code passes most of its tests, except one and I don't know where I did wrong.
The code:
#include <bits/stdc++.h>
using namespace std;
vector<int> adj;
int kStart = 0, kEnd = 0;
void getOutput()
{
ofstream output("max.out");
output << kStart + 1 << " " << kEnd + 1;
output.close();
}
void kadane()
{
int max_global = INT_MIN, max_current = 0, kS = 0;
for(int i = 0; i < adj.size(); i++)
{
max_current += adj[i];
if(max_current > max_global || (max_current == max_global && i - kS < kEnd - kStart))
{
max_global = max_current;
kStart = kS;
kEnd = i;
}
if(max_current < 0)
{
max_current = 0;
kS = i + 1;
}
}
}
void getData()
{
ifstream input("max.in");
int n; input >> n;
for(int i = 0; i < n; i++)
{
int num; input >> num;
adj.push_back(num);
}
input.close();
}
int main()
{
getData();
kadane();
getOutput();
system("pause");
}

Optimizing a program C++

I have to create a program, which counts bursted baloons, like from ZUMA. If I have a line with 3 or more baloons with the same color this sequence will burst. So in input, I have number of ballons (3 <= N <= 10^5) , and line with numbers (line with baloons color (1 <= сi <= 100) ), with 1 sequence for sure. I have to output number of bursted baloons. I have a programm, but it is working longer than 4000msv sometimes. How can I make it working faster?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int Fmax(int n, const string& f){
int max;
vector<int> k(n);
int i, j, p = 0;
for (i = 0; i <= n; i++)
{
k[i] = 0;
}
for (i = 0; i <= n; i++)
{
for (j = i; j <= n; j++)
{
if (f[i] == f[j])
{
k[p]++;
}
else break;
}
p++;
}
max = k[0];
for (i = 0; i <= p; i++){ if (max <= k[i]){ max = k[i]; } }
return max;
}
string pog(int n){
int d;
string doa;
for (int i = 1; i <= n; i++){
cin >> d;
doa += (char)d;
}
return doa;
}
void main(){
int i, sc = 1, bf = 1;
string f;
int len;
cin >> i;
f = pog(i);
len = i;
while (Fmax(f.length(), f) >= 3){
for (int c = 1; c <= f.length(); c++){
if (f[c] == f[c - 1]){
if (sc == 1){ bf = c - 1; }
sc++;
}
else{
if (sc >= 3){ f.erase(bf, sc); sc = 1; break; }
sc = 1;
}
}
}
cout << len - f.length() << endl;
}
Any help is warmly welcome.
You are leaking memory. Use vectors to avoid that.
Why do you need to create array? Why not use the string directly?
Pass strings which aren't modified by const reference to avoid copies.
Use constant variables for the lengths:
const unsigned int f_length = f.length();
while (Fmax(f_length, f) >= 3){
for (int c = 1; c <= f_length ; c++){
This helps the compiler reduce the number of calls to the length method.