i am learning recursion in C++ and as practice i was trying to write binary to decimal converter with recursive function. In following code converter is working as it should:
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int sum = 0;
int DecimalConversion (int power, int number){
int bit;
if (number == 0)
{
return 0;
}
bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
DecimalConversion(power, number);
return sum;
//return bit * pow(2, power) + DecimalConversion(power, number);
}
int main(){
int power = 0;
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(power, number);
system("PAUSE >> NULL");
return 0;
}
Is it possible to return value from DecimalCoonversion function by not using global variable? Can someone explain how, I tried next line of code but it does not work correctly:
return bit * pow(2, power) + DecimalConversion(power, number);
Can anyone explain where i am making mistake using previous line of code?
Thank You in advance
This adds sum as a parameter to your function, but makes it default to 0 if you don't provide it explictly. Power is also defaulted to 0, which saves you having to pass it into the function.
Since default parameters must be at the end of a function declarations and/or definitions parameter list, I had to move power across to achieve this.
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int DecimalConversion (int number, int power = 0, int sum = 0) // changes here
{
if (number == 0)
{
return sum;
}
int bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
return DecimalConversion(number, power, sum); // changes here
}
int main(){
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(number);
system("PAUSE >> NULL");
return 0;
}
Please note I didn't check this actually converts binary to decimal correctly, just that the recursion works.
You can call this function like so:
DecimalConversion(number);
This:
int DecimalConversion(int power, int number){
if (number == 0)
return 0;
else
return (number % 10)*pow(2, power) + dc(power+1, number/10);
}
or
int DecimalConversion(int power, int number){
return number?(number % 10)*pow(2, power) + dc(power+1, number/10):0;
}
Related
Find a sum of series by function s= 1!/y!+y!/3!+5!/y!......n
I don't know how to define fact function and is this code correct??
#include <math.h>
#include <iostream>
using namespace std;
float fact(float, float);
float sum(float, float);
int main() {
float n, x, s;
cout << "enter n and x" << endl;
cin >> n >> x;
s = sum(n, x);
cout << "sum =" << s << endl;
return 0;
}
float sum(float n, float x)
{
float x, s = 0;
for (int i = 0; i <= n; i++)
if (i % 2 == 0)
s = s + float(fact(i + 1) / fact(x));
else
s = s + float(fact(x) / fact(i + 1));
return s;
}
Whilst there are ways of defining the factorial of a floating-point number (using a gamma function), I doubt that is what you want. Similarly, the upper index n shouldn't be a float, either.
Your series as written looks awfully divergent.
As somebody else has said, it is rare to calculate new factorials from scratch: divisors of them tend to cancel, and whole terms of your series are simple multiples of earlier terms.
I am writing a program to calculate the factorial of 100. The code is as below. Notwithstanding, the output is 0 as the answer is too big. Is there any answer to display the exact answer? This is because even unsigned long long is not even able to display the factorial of 100. Thank you.
#include <iostream>
using namespace std;
int main()
{
int n,i,fact=1;
cout << "enter the number "<<endl;
cin>>n;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
cout<<"the factorial is "<<fact<<endl;
}
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 22!.
The answer will be exact.
With such an approach the calculation is simple. I do not even know what to explain further.
Please see the code:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Calculate n! Enter n (max 10000): ";
if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {
// Here we store the resulting number as single digits
std::vector<unsigned int> result(3000, 0); // Magic number. Is big enough for 100000!
result.back() = 1; // Start calculation with 1 (from right to left)
// Multiply up to the given input value
for (unsigned int count = 2; count <= input; count++)
{
unsigned int sum{}, remainder{};
unsigned int i = result.size() - 1; // Calculate from right to left
while (i > 0)
{
// Simple multiplication like on a piece of paper
sum = result[i] * count + remainder;
result[i--] = sum % 10;
remainder = sum / 10;
}
}
// Show output. Supporess leading zeroes
bool showZeros{ false };
for (const unsigned int i : result) {
if ((i != 0) || showZeros) {
std::cout << i;
showZeros = true;
}
}
}
else std::cerr << "\nError: Wrong input.";
}
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17
You can use C++ Boost Library to to manipulate such large numbers.
Here is the code:
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using namespace boost::multiprecision;
cpp_int fact(int);
int main(){
cpp_int a=1;
int n;
cin>>n;
cout<<fact(n)<<endl;
}
cpp_int fact(int x){
if(x==1)
return 1;
cpp_int temp=1;
temp= x*fact(x-1);
return temp;
}
Find below my implementation for binary exponentiation
#include<iostream>
#include<cmath>
using namespace std;
int fast_exponentiation(int base, int pow) {
unsigned int result; // variable to store intermediaries
if (pow == 1) {
return base;
}
else if (pow == 0) {
return 1;
}
result = fast_exponentiation(base, floor(pow/2));
// even power
if (pow % 2 == 0) {
return result * result;
}
// odd power
else {
return result * base * result;
}
}
int main() {
int num, answer, p;
cout << "Enter the base: ";
cin >> num;
cout << "Enter power: ";
cin >> p;
answer = fast_exponentiation(num, p);
cout << answer << endl;
return 0;
}
The problem is when I ran this for inputs num= 3 and pow = 20 I get -808182895, a negative number. I can't seem to figure out what is wrong with the code? Can I get some help?
Value of 3^20 exceeds max possible int value 2^31, so you have got overflow. The simplest way to overcome this limit is using long long data type to provide possiblity for calculations upto power 39 (near 2^63)
For larger powers one need long number arithmetics - boost multi-precision, GMP etc
Can you give me advice about precision of computing Taylor series for an exponent? We have a degree of exponent and a figure of precision calculating as imput data. We should recieve a calculating number with a given precision as output data. I wrote a program, but when I calculate an answer and compare it with embedded function's answer, it has differents. Can you advice me, how I can destroy a difference between answeres? formula of exponent's calculating
#include "stdafx.h"
#include "iostream"
#include <math.h>
#include <Windows.h>
#include <stdlib.h>
using namespace std;
int Factorial(int n);
double Taylor(double x, int q);
int main()
{
double res = 0;
int q = 0;
double number = 0;
cout << "Enter positive number" << "\n";
cin >> number;
cout << "Enter rounding error (precision)" << "\n";
cin >> q;
cout << "\n" << "\n";
res = Taylor(number, q);
cout << "Answer by Taylor : " << res;
cout << "Answer by embedded function: " << exp(number);
Sleep(25000);
return 0;
}
int Factorial(int n) {
int res = 1;
int i = 2;
if (n == 1 || n == 0)
return 1;
else
{
while (i <= n)
{
res *= i;
i++;
}
return res;
}
}
double Taylor(double x, int q) {
double res = 1;
double res1 = 0;
int i =1;
while (i)
{
res += (pow(x, i) / Factorial(i));
if (int(res*pow(10, q)) < (res*pow(10, q)))
{//rounding res below
if ( ( int (res * pow(10,q+1)) - int(res*pow(10, q))) <5 )
res1 = (int(res*pow(10, q))) * pow(10, (-q));
else
res1 = (int(res*pow(10, q))) * pow(10, (-q)) + pow(10,-q);
return res1;
}
i++;
}
}
There are two problems in your code. First, the factorial is very prone to overflow. Actually I dont know when overflow occurs for int factorials, but I remember that eg on usual pocket calculators x! overflows already for x==70. You probably dont need that high factorials, but still it is better to avoid that problem right from the start. If you look at the correction that needs to be added in each step: x^i / i! (maths notation) then you notice that this value is actually much smaller than x^i or i! respectively. Also you can calculate the value easily from the previous one by simply multiplying it by x/i.
Second, I dont understand your calculations for the precision. Maybe it is correct, but to be honest for me it looks too complicated to even try to understand it ;).
Here is how you can get the correct value:
#include <iostream>
#include <cmath>
struct taylor_result {
int iterations;
double value;
taylor_result() : iterations(0),value(0) {}
};
taylor_result taylor(double x,double eps = 1e-8){
taylor_result res;
double accu = 1; // calculate only the correction
// but not its individual terms
while(accu > eps){
res.value += accu;
res.iterations++;
accu *= (x / (res.iterations));
}
return res;
}
int main() {
std::cout << taylor(3.0).value << "\n";
std::cout << exp(3.0) << "\n";
}
Note that I used a struct to return the result, as you should pay attention to the number of iterations needed.
PS: see here for a modified code that lets you use a already calculated result to continue the series for better precision. Imho a nice solution should also provide a way to set a limit for the number of iterations, but this I leave for you to implement ;)
i wrote a code that calculates and outputs a difference between the sum of the squares of the first ten natural numbers and the square of the sum.
The problem is with function squareOfSum(). The function should return 3025 but it always returns 3024. Even if i try to put 100 into brackets i get 25502499 (25502500 is correct). No matter what number i put into brackets i always get the same problem.
What am I doing wrong?
Here's a screenshot of my output.
#include <iostream>
#include <cmath>
using namespace std;
int sumOfSquares(int limit);
int squareOfSum(int limit);
int main()
{
cout << sumOfSquares(10) << endl;
cout << squareOfSum(10) << endl;
cout << squareOfSum(10) - sumOfSquares(10) << endl;
}
int sumOfSquares(int limit)
{
int sum = 0;
for(int i = 1; i<=limit; i++)
{
sum +=pow(i,2);
}
return sum;
}
int squareOfSum(int limit)
{
int sum = 0, square = 0;
for(int i = 1; i<=limit; i++)
{
sum +=i;
}
square = pow(sum,2);
return square;
}
Note that pow is a function that works with floating point numbers. Optimizations might lead to rounding errors or truncation during implicit coversion to int. Replace pow(i, 2) with i*i and you'll get pure integer arithmetic and thus exact results.
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main()
{
int higher_limit = 100;
int SquaresOfSum = 0;
int SumOfSquares = 0,count=0;
for(int i=1;i<=higher_limit;i++){
count += i;
SumOfSquares += pow(i,2);
}
SquaresOfSum = pow(count,2);
cout<<SquaresOfSum-SumOfSquares;
}
Using Javascript
const sumSquareDifference = (n) => {
const numbers = [...Array(n + 1).keys()];
const sumOfSquares = numbers.reduce((accumulator, number) => accumulator + (number ** 2));
const squareOfSum = numbers.reduce((accumulator, number) => accumulator + number) ** 2;
return squareOfSum - sumOfSquares;
}
console.log(sumSquareDifference(10));