I have this code here that should output all squared numbers before n. For example, if you type 10, it will show 1 4 9. The problem is, when I input 25, it should've given output 1 4 9 16 25. But, instead, it shows 1 4 9 16 24
#include <iostream>
using namespace std;
#include <cmath>
int main(){
int a, b;
cin >> a;
for(int i = 1; i <= a; i++)
{
b = pow(i,2);
if (b <= a) cout << b << " ";
}
return 0;
}
if you only use integers, and squared numbers you don't need any math library for the solution, you can get the square of a number by multiplying it to itself.
And you can have better performance if you break out of the loop when you reach the first square number that is bigger than your input number, no need to calculate any more.
example code:
#include <iostream>
int main()
{
int a;
std::cin >> a;
for (int b, i = 1;; ++i)
{
b = i * i;
if (b > a)
break;
std::cout << b << " ";
}
return 0;
}
Your problem is likely caused by the pow() function. While I was not able to reproduce this error (cmath in MinGW and Visual C++ uses std::pow that has integer overloads since C++98), I believe Your compiler uses the float overload for some reason. You should try replacing b = pow(i,2) with b = i * i.
Related
I'm trying to solve Codewars task and facing issue that looks strange to me.
Codewars task is to write function digital_root(n) that sums digits of n until the end result has only 1 digit in it.
Example: 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 (the function returns 6).
I wrote some bulky code with supporting functions, please see code with notes below.
The problem - digital_root function works only if I put cout line in while loop. The function returns nonsense without this cout line (please see notes in the code of the function).
My questions are:
Why isn't digital_root working without cout line?
How cout line can effect the result of the function?
Why does cout line fix the code?
Thanks a lot in advance! I'm a beginner, spent several days trying to solve the issue.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int getDigit (int, int);
int sumDigits (int);
int digital_root (int);
int main()
{
cout << digital_root (942); // expected output result is 6 because 9 + 4 + 2 = 15 -> 1 + 5 = 6
}
int getDigit (int inputNum, int position) // returns digit of inputNum that sits on a particular position (works)
{
int empoweredTen = pow(10, position-1);
return inputNum / empoweredTen % 10;
}
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum;
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
int digital_root (int inputNum) // supposed to calculate sum of digits until number has 1 digit in it (abnormal behavior)
{
int n = inputNum;
while (n > 9)
{
n = sumDigits(n);
cout << "The current n is: " << n << endl; // !!! function doesn't work without this line !!!
}
return n;
}
I've tried to rewrite the code from scratch several times with Google to find a mistake but I can't see it. I expect digital_root() to work without any cout lines in it. Currently, if I delete cout line from while loop in digital_root(), the function returns -2147483647 after 13 seconds of calculations. Sad.
Here is an implementation using integer operators instead of calling std::to_string() and std::pow() functions - this actually works with floating-point numbers. It uses two integer variables, nSum and nRem, holding the running sum and remainder of the input number.
// calculates sum of digits until number has 1 digit in it
int digital_root(int inputNum)
{
while (inputNum > 9)
{
int nRem = inputNum, nSum = 0;
do // checking nRem after the loop avoids one comparison operation (1st check would always evaluate to true)
{
nSum += nRem % 10;
nRem /= 10;
} while (nRem > 9);
inputNum = nSum + nRem;
std::cout << "The current Sum is: " << inputNum << endl; // DEBUG - Please remove this
}
return inputNum;
}
As for the original code, the problem was the uninitialized sum variable, as already pointed out by other members - it even generates a compiler error.
int sumDigits (int inputNum) // returns sum of digits of inputNum (works)
{
int sum = 0; // MAKE SURE YOU INITIALIZE THIS TO 0 BEFORE ADDING VALUES TO IT!
int inLen = to_string(inputNum).length();
int i = inLen;
while (inLen --)
{
sum += getDigit(inputNum, i);
i --;
}
return sum;
}
Initialize your variables before adding values to them, otherwise you could run into undefined behaviour. Also for the record, adding the cout line printed out something, but it wasn't the correct answer.
The code works fine for some values like for eg 10 the output is 1010 which is correct but for 20 or 50 or 51 the output is wrong or atleast seems so to me.
please help !
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int n;
cin >> n;
int ans = 0;
int i = 0;
while (n != 0)
{
int bit = n & 1;
ans = (bit * pow(10, i)) + ans;
n = n >> 1;
i++;
}
cout << " Answer is " << ans << endl;
}
change datatype of ans.
float ans = 0;
After trying to run your code, it works. 51 correctly comes out as 110011 and 50 as 110010 and 20 as 10100. Those are the correct bit values, you can try calculating them by counting or by just adding 10 (i.e. 1010) in different ways.
The Problem Statement is:
You've to display the digits of a number.
Take as input "n", the number for which digits have to be displayed.
Print the digits of the number line-wise.
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int n;
cin>>n;
int nod = 0;
int temp = n;
while(temp != 0){
temp = temp / 10;
nod++;
}
int div = (int)pow(10, nod - 1);
while(div != 0){
int dig = n / div;
cout<<dig<<endl;
n = n % div;
div = div / 10;
}
return 0;
}
For input 65784383, the expected output is:
6
5
7
8
4
3
8
3
However the ouput from the program is not as expected. Where did it go wrong?
Maybe you get wrong output, I don't know, you didn't say why you think there is something wrong with the code.
I do get correct output here: https://godbolt.org/z/xsTxfbxEx
However, this is not correct:
int div = (int)pow(10, nod - 1);
pow is not for integers. I suggest you to read documentation and this, and consider what happens when you truncate a floating point number to an integer.
To print linewise digits of a number given by the user all you need is this:
#include <iostream>
#include <string>
int main() {
std::string input;
std::cin >> input;
for (const auto& c : input) std::cout << c << "\n";
}
Maybe you consider this cheating and insist on doing the maths. Then collect the digits from back to front and print in reverse order, thats much simpler:
#include <iostream>
#include <vector>
int main() {
int n;
std::cin >> n;
std::vector<int> digits;
while (n) {
digits.push_back(n % 10);
n /= 10;
}
for (auto it = digits.rbegin(); it != digits.rend(); ++it){
std::cout << *it << "\n";
}
}
PS: Do not use c-style casts like you do here
int div = (int)pow(10, nod - 1);
//^^
Actually it is superfluous here, because assigning a floating point number to an int already does the truncation. Though, also in general c-style casts are to be avoided. As far as I know, the only reason they are allowed is backwards compatibility. If you do need to cast you should use static_cast. Most of the time c-style casts merely silence compiler warnings or errors and hide problems in the code.
I know there are many examples of this problem but I tried to write a different one myself.
This is using the Taylor series e^x = 1 + x/1! + x^2/2! + x^3/3! + ......
My code compiles and runs but it wont output the correct answer for some imputes and I'm not sure why. is this even usable code or should i scrap it?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double final,power,end_n = 1.0,e=1.0,x=2.0, n;
cout<< "n: ";
// usually enter 5 for test
cin>> n;
while (n>1){
power = pow(x,n);
end_n = end_n*n;
e= (power/end_n)+e;
n--;
}
final =e+x;
cout<< final;
return 0;
}
I honestly have no idea what your reasoning is, at all. The code for that particular expansion is trivially simple:
double x;
cin >> x;
double oldres, res=1, top=1, bottom=1;
int iter=1;
do {
oldres=res; // to calculate the difference between iterations
++iter; // next iteration
top*=x; // multiply by one x for each iteration
bottom*=(iter-1); // multiply by the iteration number for each iteration
res+=top/bottom; // and add the fraction to the result
} while(fabs(res-oldres)>.1); // while the difference is still large
cout << res; // done, show the result
To be very clear about something that others are hinting at: if your loop counted up from 1 to n then end_n would equal n! at each step. But counting down, it doesn't. Look at the examples from 1 to 5:
Forwards
n | n!
1 | 1
2 | 2
3 | 6
4 | 24
5 | 120
Backwards
n | end_n
5 | 5
4 | 20
3 | 60
2 | 120
1 | 120
Since absolutely none of your denominators are right, it's a surprise if your code is only wrong for some inputs — in fact it's probably only correct for x=0.
Finally, I hope that this is just an exercise for learning. If you really need the value of e^x you should use exp(x).
I think you are close. Maybe you want something more like this:
#include <iostream>
#include <cmath>
using namespace std;
double factorial(long n)
{
double result = n;
while(--n) result*=n;
}
int main()
{
long n, power;
double final, e=1.0, x=2.0;
cout<< "n: ";
// usually enter 5 for test
cin>> n;
while (n>1)
{
power = pow((double)x, (double)n);
end_n = factorial(n);
e = (power/end_n)+e;
n--;
}
final = e+x;
cout<< final;
return 0;
}
You could actually employ a Horner-like scheme that uses the counting down in an essential manner
1 + x/1! + x^2/2! + x^3/3! + … + x^n/n! = (((((x/n+1)*x/(n-1)+1)*x/(n-2)+…)*x/1+1
e = 1.0;
while (n>0){
e = e*x/n + 1;
n--;
}
Compare the approximations of e^x and 1/(e^-x) for positive x for exactness.
Explore (e^(x/4))^4 for better exactness.
I was writing a small snippet to get a Fibonacci number sequence depending on the user input. If the user supplies 4 as an input, it should return him the first N members of the Fibonacci sequence.
#include <iostream>
using namespace std;
int main (){
int a = 0;
int b = 1;
int c;
int n = 3;
n -= 2;
if (n == 1){
cout << a << endl;
} else {
cout << a << b << endl;
for (int i=0;i<n;i++){
c = b + a;
cout << c << endl;
a = b;
b = c;
}
}
}
However, I end up getting a 0 as an output for whatever number I supply. I have this working in PHP and I kinda miss where I've blundered. I guess I don't actually render input and output properly.
int a =0;
int n = 3;
n -= 2;
if (n == 1){
cout << a << endl;
}
You have n equal to 3, you subtract 2, thus n equal to 1, so, you enter the if body and output a, which is zero.
[EDIT]
You don't seem to get any input -as stated in a comment- in your program (you could use std::cin or std::getline() for this), but you probably mean that you have the input hard-coded, by changing the value of n by hand.
You may want to check how the Fibonacci series program is expected to work:
Fib. at Rosseta page.
Fib. with recursion
Non-recursive Fib.
After reading the links I provided above, you should be able to see that your code should be changed to this:
#include <iostream>
using namespace std;
int main (){
int a = 1;
int b = 0;
int c;
int n = 10; // "input" is 10
if (n == 0 || n == 1) { // 0 and 1 case
cout << n << endl;
} else {
for (int i = 2; i <= n; ++i) { // here you want to reach n
c = a + b;
b = a;
a = c;
}
cout << c << endl;
}
return 0;
}
However, the code above outputs only the result. You should slightly modify it to get the terms of the sequence, but I'll leave you have some fun too.
In order to really let the user input the number, change:
int n = 10;
to
int n;
std::cout << "Please, input.\n";
std::cin >> n;
However, letting user inputting must be followed by validation of the input. You see users can, by accident or not, provide input in your program, that can cause undefined behaviour.
The sequence you want is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, ...
As I pointed out in a comment to another answer, your code does not produce a correct Fibonacci sequence. F(3) isn't the problem with your code; the problem is that you get confused between all the variables, a, b, c and use them to mean different things at once.
You also incorrectly decrement n: your code does it in the wrong place, and even if you move it to the right place, it wouldn't help as the operation would make n go negative.
Your existing Code
Let's walk through your code a bit:
int a = 0;
int b = 1;
int c;
int n = 3;
n -= 2;
Well, this is weird. We set n to 3 then immediately subtract 2, making it 1. This means that if you try to set n to 0, 1, or 2 you end up with n being a negative number. If you set it to 3, you end up with n being 1.
if (n == 1){
cout << a << endl;
}
We're in trouble right here. Remember that you subtract 2 from n which means that for n==3 you will return whatever is in a which is wrong. But even if you meant this to special-case F(1) that code is still wrong because F(1)=1.
else {
cout << a << b << endl;
for (int i=0;i<n;i++){
Remember, that we can get here with n zero or negative. Obviously in the case of n <= 0 this loop will never execute, so c will never be printed.
c = b + a;
cout << c << endl;
Here, we seem to calculate and output the next Fibonacci number by adding the two previous numbers. This should be fine.
a = b;
b = c;
And here, we keep the new Fibonacci number and its predecessor for the next loop iteration, if any.
The problems with this code are, of course, fixable. But the problem is that the existing code is confusing. It outputs all sorts of different values, and it's unclear what variable is supposed to represent.
Looking at this problem, your first instinct would be to make a function which accepts as input a number n and returns F(n) - you could call it fib or somesuch.
Reworking this
So, how to go about writing such a function? Here's a simple recursive implementation that you can use:
int fib(int n)
{
if ((n == 0) || (n == 1))
return n;
return fib(n-1) + fib(n-2);
}
Notice how this function is short, sweet and to the point. There's no need for a ton of variables, no need for complicated control structures or storing state. It almost reads like a text-based description of the Fibonacci algorithm.
Of course, it's not super-efficient and ends up redoing a lot of work. That's a legitimate criticism, but it's unlikely that there performance considerations here.
Still, perhaps you just don't like recursion. Many people think of recursion as a dirty word, and avoid it with a passion. So how about a non-recursive implementation instead? It's possible, but it's a bit more difficult to understand.
int fib (int n)
{
/* F(0) = 0 */
if (n == 0)
return 0;
int a = 0;
int b = 1;
for (int i = 2; i < n; i++)
{
int c = a + b;
a = b;
b = c;
}
/* F(n) = F(n-2) + F(n-1) */
return a + b;
}
This is a little bit more efficient and not that much more difficult to understand.
I hope that this helped.
Try this which would give you the list you needed.
#include <iostream>
using namespace std;
int fib(int num){
int ans;
if (num >2) {
ans = fib(num-1) + fib(num-2);
}
else
ans = 1;
return ans;
}
int main()
{
int num, x=1;
cin >> num;
while (num >= x) {
cout << fib(x) <<" ";
x++;
}
return 0;
}