Incorrect mathematical results calculating power series [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
#include <iostream>
#include <cmath>
using namespace std ;
int main ()
{
int n, sum=0 ;
cout<< "Input number of terms: " ;
cin>> n ;
for (int i=1; i<=n; i++)
{
int k = pow(10, i) - 1 ;
cout << k ;
if(i < n)
{
cout<< " + " ;
}
sum += k ;
}
cout << "\nThe sum of the series = " << sum ;
{int m;cin>>m;}
return 0 ;
}
every time I run this code it gives me weird output like
9 + 98 + 999 + 9998 + ...
it subtracts some Ks from 2 !!
The rule is mathematically right and there is no syntax errors.
Is it the way of declaring k inside the loop or it's an compiler error ?
So, what's wrong here?

Here is the for loop without using the pow function:
int power = 10;
for (int i = 1; i < n-1; ++i)
{
const int k = power - 1 ;
cout << k;
if(i < n)
{
cout<< " + " ;
}
sum += k;
power *= 10; // This is important.
}
This should be more accurate than using pow because there is no conversions between integer and floating point.
Also, you may want to try using the series from 0 .. (n-1).

I think the best thing to do is to create your own power function because pow() is not working that way before when I used it. Kinda like this one
int pow_num(int base_num, int exp_num)
{
int result = 1;
for(int i = 0; exp_num > i; ++i)
{
result = result * base_num;
}
return (result);
}

Related

I Submitted the solution and got time limit error in 4th test case [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 4 years ago.
Improve this question
This is a problem on codeforces
and I have submitted a solution and I got TLE.
How to remove TLE
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
unsigned int y, k, n;
set <int> s;
cin >> y >> k >> n;
if (y >= n)
{
cout << -1; return 0;
}
for (int i = y + 1; i <= n; i++)
{
if (i%k == 0)
{
s.insert(i - y);
}
}
if (s.begin() == s.end())
{
cout << -1; return 0;
}
for (auto x : a)
cout << x << " ";
}
The problem seems at the algorithmic level. Instead to generate all candidate i values and then test if they are divisible by k, you can directly generate these values in a loop with an increment equal to k.
The minimum value iminis equal to k*((y+1)/k) or k*((y+1)/k) + k, depending if y+1 is divisible by kor not.
You have two gains: you consider k less candidates, and you avoid the costly % operation.
Moreover, when you find a value, you can directly print it, no need to memorize it.
Edit: here is the code
#include <iostream>
int main()
{
std::ios::sync_with_stdio(false);
unsigned int y, k, n;
std::cin >> y >> k >> n;
unsigned int imin = k*((y+1)/k);
if (imin < y+1) imin += k;
if (imin > n) {
std::cout << -1;
return 0;
}
for (unsigned int i = imin; i <= n; i+=k)
{
std::cout << i-y << " ";
}
return 0;
}
Edit 2: the last i-y calculation can be avoided by changing the bounds of the loop

My c++ programm in Visual Studio closes without reading FOR function; [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
Can someone tell me why this programm gives only the cout text?
#include "iostream"
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
float x;
int y[50];
int n;
cout << "Dati notele despartindule prin Enter";
for ( n = 0; n == 5; n++) {
cin >> y[n];
if (n >= 1) {
y[n] = y[n - 1] + y[n];
}
}
x = y[n] / (n + 1);
cout << x;
return 0;
}
for ( n = 0; n == 5; n++)
Is not what you want. A for-loop is nothing but a while-loop using different syntax:
n = 0;
while(n == 5)
{
// you loop body here
n++;
}
As you can see, it executes while your condition is true. In this case... not at all because it's not true to begin with.
You probably meant
for ( n = 0; n < 5; n++)
n == 5 is the problem. When came to for function and makes the test to see if the block needs to run it get false because you initialize with n = 0; better than n == 5 use n!=5 but if you skip to make n = 5 you get an infinite loop.
For the best case use n < 5.

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

C++ program to find the largest palindrome which is product of two two digit numbers [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 8 years ago.
Improve this question
I have seen this, but this is not what I am looking for.
The problem is same that is to find the largest palindrome which is the product of two three digit numbers.
Since my program was not working so I made a little change, instead of finding the largest palindrome which is the product of two three digit numbers I have written the program to find the largest palindrome which is the product of two two digit numbers.
Kindly see the program:
#include <iostream>
using namespace std;
int main() {
int i, j, n, s, m, w;
for (i = 99; i > 9; i--) {
for (j = 99; j > 9; j--)
n = i * j;
s = n;
while (n != 0) {
w = 0;
m = n % 10;
w = w * 10 + m;
n = n / 10;
}
if (s == w)
cout << s << endl;
break;
}
return 0;
}
The problem with this program is that it is neither showing any error nor giving any result.
So kindly help me to find the problem in my program.
Right now you are missing the curly braces for the j-loop. The current code is doing 99! * i.
Then you would have to focus on storing the largest palindrome value instead of just printing all those values to the screen (this is considering your implementation, it is not the most efficient one by any means).
Some modified version of your code:
#include <iostream>
using namespace std;
int main() {
int max_product = 0;
for (int i = 99; i > 9; i--) {
for (int j = i; j > 9; j--) {
int product = i * j;
if (product < max_product)
break;
int number = product;
int reverse = 0;
while (number != 0) {
reverse = reverse * 10 + number % 10;
number /= 10;
}
if (product == reverse && product > max_product) {
max_product = product;
}
}
}
cout << "Solution: " << max_product << endl;
return 0;
}
You have various problems:
Need one more pair of {, }. After the for-loop of j. The only instruction the for-loop of j is executing is: n = i * j; with the braces the rest of the instruction (testing if it's a palindrome) are out of the loop.
the variable w the reverse of the number to test for palindrome is reset his value to 0 in every execution of while (n != 0) loop resulting in incorrect reverse value (and never find the palindrome).
The max palindrome product of 2 two digits number don't have to be the first one found with this 2 for-loop, eg: suppose that there is 2 valid solutions i = 98, j = 2 and i = 70, j = 65 in this case i*j would be in first solution = 196 in the second = 4550 and when you found the first you could not stop the search. In your code using the break don't do what I think you are waiting for (stop the search), only stop the search with the actual i value.
Some notes about the modified code:
The two for-loop don't need to be from 99..9, in this case you are testing a lot of product two times (eg: 98*99, are testing when i == 98 and j == 99 and i == 99 and j == 98), you could restrict j to be always less or equal to i.
Using max_product to maintain the maximum palindrome product found. And use that info in the inner loop (if (product < max_product)) for early exit when no better solution could be found.

How to make this algorithm faster? [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 8 years ago.
Improve this question
I am trying to come up with the following algorithm:
The input is unsigned integer number.
The output is the size of the array of unordered pairs of unsigned integers, which, when multiplied, give a number less then or equal to the input.
I have one naive implementation working, but it is way too slow for my purpose (compl. O(n^2), please correct me if I am wrong). My question is: how to make it faster?
#include <iostream>
using namespace std;
bool notInYet(int t[][1], int mi, int ma, int m) {
bool val = true;
for(int i = 0; i < m; i++)
if(t[i][0] == mi && t[i][1] == ma)
val = false;
return val;
}
int main() {
int n, m;
int t[100000][1];
cin >> n;
m = 0;
for(int i = 1; i <= n; i++) {
for(int j = 1; j*i <= n && j <= i; j++) {
if(notInYet(t, j, i, m)) {
t[m][0] = j;
t[m][1] = i;
//cout << "t[" << m << "] = (" << t[m][0] << ", " << t[m][1] << ")" << endl;
m++;
}
}
}
cout << m << endl;
return 0;
}
I think it should be something like that - pseudocode:
int counter = 0;
for int i = 1 to sqrt(input), i++ {
if (input % i == 0) counter++;
}
counter is an answer if you need unique pairs, otherwise you need to multiply it by 2 (and sub 1 if input % sqrt(input) == 0)
If I'm reading correctly #jauser's algorithm doesn't get what you want.
If the target is 5, then the pairs are (1,1)(1,2)(1,3)(1,4)(1,5)(2,2). So the answer is 6. His algorithm will produce 1 because 5 mod 1 == 0, but not mod 2.
In general, if the target is n, then you know (1,k) is a counted pair for all k from 1 to n. There are n - 1 + 1 = n of these. Now you have (2,k) for k from 2 to floor(n/2) (skip 1 because your pairs are unordered). There are n/2-2+1 of these. Continue this through (j,k) for j= floor(sqrt(n)). Putting this is pseudocode
count = 0;
for j in 1 .. floor(sqrt(n))
count += floor(n / j) - j + 1;
Maybe there is even some clever series solution that gets this to a constant time calculation.
Am I missing something in the problem?
Well, you are spending a lot of time effectively calculating the following per i:
j= n/i;
So if you just do that you reduce the complexity to O(n). You can halve it also since the list will contain both (i, j) and (j, i) when i!=j, but that won't reduce the overall complexity.