how can we merge elements of an array in c++? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to make a c++ program that merges the elements of an array For example we have three elements that are 2 5 7 and we want merge them make a number 257

Most efficient solution:
#include <iostream>
using namespace std;
int main()
{
const int N = 3;
int a[N] = {2,5,7};
int num = 0;
for(int i=0;i<N;i++)
num = num * 10 + a[i];
cout << num << endl;
return 0;
}
steps:
num -> 0
num -> 2
num -> 25
num -> 257

The simplest way is to use the range based for statement. For example
int a[] = { 2, 5, 7 };
int x = 0;
for ( int digit : a ) x = 10 * x + digit;
Here is demonstrative program
#include <iostream>
int main()
{
int a[] = { 2, 5, 7 };
int x = 0;
for ( int digit : a ) x = 10 * x + digit;
std::cout << "x = " << x << std::endl;
return 0;
}
The output is
x = 257
The same can be done using standard algorithm std::accumulate declared in header <algorithm>
Take into account that the array has to have acceptable values like digits and that the resulted number would not overflow the acceptable range of values for the given type of the accumulator.

#include <iostream>
#include <cmath>
int main()
{
const int N = 3; // the size of the array
int a[N] = {2,5,7};
// define the number that will hold our final "merged" number
int nbr = 0;
// loop through the array and multiply each number by the correct
// power of ten and add it to the merged number
for(int i=N-1;i>=0;--i){
nbr += a[i] * pow(10, N-1-i);
}
// print the number
std::cout << nbr << std::endl;
return 0;
}

Related

How find the count integers that are divisible by 7 in the given range using only While loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
---How write a program that will get A and B inputs and the numbers in the [A, B] range will be divisible by 7 without the remainder... using while loop in C++...---
For Example:
Input data: 7 13
console result: 1
Input data 5 21
console result: 3
Input data -8 -5
console result: 1
C++ code example with for loop
int main() {
int a, b,i,count;
input >> a >> b;
count = 0;
for(i = a; i <= b; i++) {
if(i % 7 == 0)
count++
}
}
I'm not sure if this is pseudo-code or actual code, but the main mistake I see here is that you've used 'input' and I'm not sure what that's supposed to be. See the following example:
#include <iostream>
using namespace std;
int main() {
int count=0;
int a = 0;
int b = 0;
cin >> a >> b;
for(int i = a; i <= b; i++) {
if(i % 7 == 0) {
count++;
}
}
cout << count;
}
I replaced your 'input' with 'cin'. Then, I added an output of the 'count' variable so that we could see the result.
Now, to take it further and use a while loop, you just need to manually count:
#include <iostream>
using namespace std;
int main() {
int count=0;
int a = 0;
int b = 0;
cin >> a >> b;
while (a <= b) {
if (a % 7 == 0) {
count++;
}
a = a +1;
}
cout << count;
}
So, we simply need to say while a is less than or equal to b, do the same thing as before. But, make sure that you increase a, or your loop will go on forever!
Everything is correct in terms of pseudo code. Do you want the negative number to be included or not?
Anyway, I am counting negative numbers also.
#include <iostream>
int main()
{
int a, b, i, count = 0;
std::cin >> a >> b;
i = a;
while (i <= b) // While loop
{
if (i % 7 == 0)
{
count++;
}
i++;
}
std::cout << "Count: " << count << "\n";
return 0;
}

Find palindrome with algorithm [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am given a number N<=200 and I need to find palindrom using ONLY this algorithm and output the palindrom and number of iterations:
1)Reverse nember
2)Revers number + previous one
Examples:
1) N=99
Out 99 0
2) N=69
69+96=165 165+561=726 726+627=1353 1353+3531=4884
Out:4884 4
My code:
#include <iostream>
using namespace std;
int rev(int a)
{
int b = 0;
while (a)
{
b = 10 * b + a % 10;
a /= 10;
}
return b;
}
int main()
{
ios::sync_with_stdio(0);
int n, c = 0;
cin >> n;
while (n != rev(n))
{
n = n + rev(n);
c++;
}
cout << n << endl << c;
return 0;
}
It works only for 70 tests out of 100:(
Can you help me so that it works for all tests?
It is simply a problem of integer overflow. A first implementation was realized with unsigned long long. It seemed to work but some overflows were not detected.
A new implementation was performed with __int128. Moreover, a signed version was used in order to be able to detect overflow easily.
Now, for n between 1 and 200, all palindromes are found, except for n = 196, for which an overflow is detected.
Here is the program:
#include <iostream>
//using namespace std;
void print128 (__int128 a) {
__int128 v64 = (__int128) 1 << 64;
__int128 high128 = a / v64;
__int128 low128 = a % v64;
unsigned long long high = high128;
unsigned long long low = low128;
if (high > 0) std::cout << high;
std::cout << low;
}
__int128 rev(__int128 a) {
__int128 b = 0;
while (a) {
b = 10 * b + a % 10;
a /= 10;
}
return b;
}
int main() {
//std::ios::sync_with_stdio(0);
int nerr = 0;
int cmax = 100000;
for (int n0 = 10; n0 <= 200; n0++) {
bool overf = false;
int c = 0;
__int128 nrev;
__int128 n = n0;
while ((n != (nrev = rev(n))) && (c < cmax)) {
if (nrev < 0) overf = true;
n = n + nrev;
if (n < 0) overf = true;
c++;
}
std::cout << "n = " << n0 << " ";;
if ((c == cmax) && !overf) {
std::cout << " ERR0R\n";
nerr++;
} else if (overf) {
std::cout << " OVERFLOW\n";
nerr++;
} else {
std::cout << " palym = ";
print128 (n);
std::cout << " c = " << c << "\n";
}
}
std::cout << "Nbre of errors = " << nerr << "\n";
return 0;
}
The question is "what to do for the 196 case ?" We don't know if a solution exists, i.e. if there is convergence. Moreover, if it converges, we don't know what the size of the palindrome could be. Trying to use int with more bits can be a long race. What is better will be to implement a dedicated int type adapted to the problem, i.e. a vector of int, each int between 0 and 9. We only have two operations to perform for this algorithm, calculating a palindrome and an addition. Calculating a palindrome will be trivial, inverse the elements of the vector (ignoring first zeros), and an addition will be rather easy to implement. Moreover, such an addition will easily detect overflow. Last but not least, the size of the vector could be adaptable for each n value, until a given limit.
EDIT: In a comment, Mark Ransom provided a link to Wikipedia page on Lychrel numbers, i.e. numbers for which the algorithm will not converge. 196 is the lowest and most famous "candidate Lychrel" number. It is conjectured, not proved, that 196 is such a number. Experiments have been performed until billions of digits, not finding a convergence for this number.

C++ [Recursive] Write a number as sum of ascending powers of 2 [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 5 years ago.
Improve this question
So as the title says,I have to write a number as sum of ascending powers of 2.
For instance, if I input 10, 25 , 173
10 = 2 + 8
25 = 1 + 8 + 16
173 = 1 + 4 + 8 + 32 + 128
So this is what I have done:
#include <iostream>
using namespace std;
int x,c;
int v[500];
void Rezolva(int putere)
{
if(putere * 2 <= x)
Rezolva(putere * 2);
if(x - putere >= 0)
{
c++;
v[c] = putere;
x -= putere;
}
}
int main()
{
cin >> x;
c = 0;
Rezolva(1);
for(int i = c; i >= 1; i--)
cout << v[i] << " ";
return 0;
}
I have a program which gives my code some tests and verifies if it's correct. To one test, it says that I exit the array. Is there any way to get rid of the array or to fix this problem ? If I didn't use the array it would have been in descending order.
The error isn't a compiler error.
Caught fatal signal 11 is what I receive when my program checks some tests on the code
For values higher than 10^9 the program crashes so you need to change from int to long long.
#include <iostream>
using namespace std;
long long x,c;
long long v[500];
void Rezolva(long long putere)
{
if (putere * 2 <= x)
Rezolva(putere * 2);
if (x - putere >= 0)
{
v[c++] = putere;
x -= putere;
}
}
int main()
{
cin >> x;
c = 0;
Rezolva(1);
for(int i = c - 1; i >= 0; i--)
cout << v[i] << " ";
return 0;
}
All in all, a simple overflow was the cause.
It was a simple overflow. And by the way a way easier way to do it is have a long long unsigned int
#include <bitset>
unsigned long long x = input;
std::cout << x << " = ";
std::string str = std::bitset<64>(x).to_string();
for (int i = str.size()-1; i >= 0; --i)
if(str[i]-'0')
std::cout << (2ull << i) << " + ";
if (x)
std::cout << char(8)<<char(8) << std::endl; //DELETING LAST "+" for non-zero x
else
std::cout << "0\n";
If you have a fixed size integer (e.g. int etc.) then you can just start at the greatest possible power of two, and if your number is bigger than that power, subtract the power of 2. Then go to the next power of two.
This is similar to how you would normally write numbers yourself starting from the most significant digit. So also works for how numbers are printed in base 16 (hex), 10, binary literals, etc.
int main() {
unsigned x = 173;
std::cout << x << " = ";
bool first = true;
// get the max power from a proper constant
for (unsigned power = 0x80000000; power > 0; power >>= 1)
{
if (power <= x)
{
if (!first) std::cout << " + ";
std::cout << power;
x -= power;
first = false;
}
}
assert(x == 0);
std::cout << std::endl;
}
Outputs:
173 = 128 + 32 + 8 + 4 + 1

How to calculate how many times a number goes into another number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
This is the program with the initial 'number' stated in the question taken as 'n' and the 'other number' taken as 10.
void divideme()
static int count=0; //initalised a variable which I'll be returning the value of.
int n;
cin>>n;//taken input of variable which I want to divide by another number (say 10 in this case)
int &rem=n;//created a reference variable which stores the value of n.
while (rem>=10) {
rem=rem%10; //this is to be corrected as rem = rem - 10;
count++;
}
return count;
Your code is overkill. Just do the division one time. The result is the number of times 10 goes into the number. No loop is needed at all. The % operator gives you the modulus (remainder) of a division, which is not what you need in this situation.
int divideme()
{
int n;
cin>>n; //get input which I want to divide by another number (say 10 in this case)
return (n / 10);//return how many times it divides by 10
}
For example:
9 / 10 = 0
9 % 10 = 9
10 goes into 9 0 times, with a remainder of 9.
12345 / 10 = 1234
12345 % 10 = 5
10 goes into 12345 1234 times, with a remainder of 5.
The % operator give you the modulus, which is the remainder after division.
If you just want to count the number of times that 10 goes into a number rem, then replace
rem=rem%10;
with
rem = rem - 10;
in your loop.
(Also, you don't need if (rem>=10) in your code. The while loop takes care of this.)
#include <cmath>
#include <iostream>
int times_divided_by_10(int x)
{
return int(std::log10(double(x)));
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}
expected output:
2
another way:
#include <iostream>
int times_divided_by_10(int x)
{
int count = 0;
while (x >= 10) {
++count;
x /= 10;
}
return count;
}
int main()
{
std::cout << times_divided_by_10(101) << std::endl;
}

Two Q. That were on my Procedural Programming exam no one answered correctly [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
By the way, this was a written exam. These questions gave 4 points each out of a possible 100.
Question 1:
Write a small program that by using a single while-loop and an if-statement will print out the following on the screen: [warning: multiple numbers out in a string, or hard-coding the values into variables will give zero points]
1 4 9 16 25
1 4 9 16
1 4 9
1 4
1
Question 2:
Below is the equation for the Harmonic Mean. Write a small program that can take values of an array and calculate the harmonic mean of these.
x = n * ( n Sigma i=1 (1/xi) )
Do you have any answers?
Question 1:
#include <iostream>
int main()
{
int i = 1;
int j = 5;
while(j > 0)
{
std::cout << i*i << " ";
if(i == j)
{
i = 1;
--j;
std::cout << "\n";
}else
{
++i;
}
}
}
Output:
1 4 9 16 25
1 4 9 16
1 4 9
1 4
1
Good enough?
Live example
Since recursion was not forbidden one could try this:
#include <iostream>
void printLn(int i) {
int j = 0;
while(++j <= i)
std::cout << j*j<<" ";
std::cout << "\n";
if(i > 1)
printLn(i - 1);
}
int main() {
printLn(5);
}
See it working at: http://ideone.com/mrKUx0
It uses recursion to print the individual lines and the while loop to print each number in the lines. The if is used to abort the recursion when finished.
The other code is very straight forward:
#include <iostream>
const int ARRAY_SIZE = 5;
int main() {
float array[ARRAY_SIZE] = {1, 2, 3, 4, 5};
float sum = 0;
for(int i = 0; i < ARRAY_SIZE; ++i)
sum += 1 / array[i];
std::cout << "Harmonic Mean: " << ARRAY_SIZE / sum;
}
Again see: http://ideone.com/GQJqQn
Note that the harmonic mean is defined as n/Sum(...) not n * Sum(...)