funtion
I have been trying too loop the "1 + 1/3 + 1/5 + ... + 1/n" part in the screenshot inside my code but could not do it all.
The compiler calculates 'x' which is the factorial correctly the only problem for me now is looping the fractions in the function.
int main()
{
int i=1,n,x=1; //x : factorial
double f;
cout<<"Enter an odd number : "<<endl;
cin>>n;
if (n%2==0)
{
cout<<"You have to enter an odd number."<<endl;
}
else
{
while(i<=n)
{
x = x * i;
f = x*(1+(1.0/n)) ;
i+=1;
}
}
cout<<"f = "<<f<<endl;}
Here is your answer
#include <iostream>
using namespace std;
int main()
{
int n;
double f = 1;
cout<<"Enter an odd number : "<<endl;
cin >> n;
if ( n%2 == 1)
{
double temp = n;
while ( temp > 1 ) // this one calculates factorial,
{
f *= temp;
temp--;
} // f = n!
temp = 1;
double result = 0;
while ( temp <= n ) // this one calculates (1 + 1/3 + ... + 1/n)
{
result += ( 1 / temp );
temp += 2;
} // result = (1 + 1/3 + ... + 1/n)
f = f * result; // f = n! * (1 + 1/3 + ... + 1/n)
cout<<"f = "<<f<<endl;
}
else
cout<<"You have to enter an odd number."<<endl;
return 0;
}
You need to operate on the same types of data ;)
Hey I have Modified your code, you can run it and can match your Result with Calulator
#include <iostream>
#include <math.h>
using namespace std;
int odnumber(int num);
int calFactorial(int num);
int main() {
int oddNumber, i = 1;
float temp=0, temp2 = 0, f = 0.0;
do
{
cout << "Enter the Odd Number: " << endl;
cin >> oddNumber;
} while (oddNumber%2 == 0);
while (i <= oddNumber)
{
if (odnumber(i))
{
temp = (double)(1.0/i);
temp2 +=temp;
}
i++;
}
f = calFactorial(oddNumber)*temp2;
cout << "F is = " << f << endl;
return 0;
}
int odnumber(int num) {
if (num % 2 != 0)
{
return 1;
}
else
{
return 0;
}
}
int calFactorial(int num) {
int x = 1, i = 1; //x is Factorial
while (i <= num)
{
x = x * i;
i++;
}
return x;
}
This is the Output: Run on my Machine
Related
Using C++ have written foloowing :
#include <iostream>
using namespace std;
int main()
{
int m,n;
int threemin, twomax;
threemin = 1; twomax = 1;
cout<<"Enter m"<<"Enter n";
cin>>m>>n;
int i,j;
for ((i = 1, j = 1) ; ( (i <= m), (j <= n) ) ; (i++,j++))
{
if (m>n){ i <= n ; threemin = threemin*3;} // for changing max value of i if m > n because we want to print 3^min(m,n)
else { threemin = threemin*3 ;} ; //
if (m>n){ j <= m ; twomax = twomax*2;} // same for changing j
else { twomax = twomax*2 ; }
}
cout<<"Threemax is"<<threemin<<"Twomax is"<<twomax;
return 0;
}
Issue -
For example m = 4 and n = 3 but here max(4,3) = 4 and min(4,3) = So, I have tried to such code which will give 3^min(m,n) and 2 ^max(4,3).
But Output comes out to be threemin = 3^3 = 81 and twomax = 2^3 = 8. Both are taking n as their exponent.
I am beginner .Kindly help me rectifying .
You can instead do something like this:
#include <iostream>
using namespace std;
int main()
{
int m, n, lesser, greater, threemin=1, twomax=1, i=1;
cout << "Enter m " << "Enter n";
cin >> m >> n;
lesser = min(m, n); // find smallest
greater = max(m, n); // find largest
while(i <= lesser) { // ride on smallest untill done
threemin *= 3;
twomax *= 2;
i++;
}
while(i <= greater) { // continue for largest
twomax *= 2;
i++;
}
cout << "Threemin is: " << threemin << ", Twomax is: " << twomax;
return 0;
}
So, I need to implement TheSameDigit() function, basically this function needs to print out all combinations of numbers that has the same digits. TheSameDigit function MUST be recursive and use NoDigits() and DelDigit() functions.
NoDigits(int x) => This function will return the number of digits
input: 123, output: 3
DelDigit(int x, int delD) => This function return an int which value is x, but having the delD-digit removed.
input: x = 789, delD = 2, output = 79
TheSameDigit() => The function to prints the combination of numbers with the same digits(it does not work currently).
Input: 123
Output:
123
231
132
312
213
321
#include <iostream>
using namespace std;
int NoDigits(int x);
int DelDigit(int x, int delD);
void TheSameDigits(int x, int i, int origin, bool firstTime);
int main() {
int num;
cout << "Please input an integer: ";
cin >> num;
cout << "All integers have the same digits with " << num << " are: " << endl;
TheSameDigits(num, 1, num, 1);
}
int NoDigits(int x) {
if (x == 0) {
return 0;
}
return 1 + NoDigits(x / 10);
}
int DelDigit(int x, int delD) {
int size = NoDigits(x);
int reverse = 0;
for (int i = 0; x != 0; i++, x /= 10) {
if (i != size - delD) {
int digit = x % 10;
reverse = reverse * 10 + digit;
}
}
int newNum = 0;
for (int i = 0; reverse != 0; i++, reverse /= 10) {
int digit = reverse % 10;
newNum = newNum * 10 + digit;
}
return newNum;
}
void TheSameDigits(int x, int i, int origin, bool firstTime) {
const int size = NoDigits(origin);
// Base case
if (origin == x && !firstTime) {
return;
}
if (i == size) {
i = 1;
}
// Find the removed digit
int temp = x;
int removedDigit;
for (int j = 0; temp > 0; j++, temp /= 10) {
if (j == size - i) {
removedDigit = temp % 10;
break;
}
}
// Calculate the next combination
int nextNum = (DelDigit(x, i) * 10) + removedDigit;
cout << nextNum << endl;
TheSameDigits(nextNum, i + 1, origin, false);
}
Can someone help me implement TheSameDigit function or give me an idea about it?
Thank you!
So far I have this code. I'm trying to print prime factorization with exponents. For example, if my input is 20, the output should be 2^2, 5
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors (int n);
bool prime( int n);
int main(int argc, char** argv) {
int n = 0 ;
cout << "Enter a number and press Enter: ";
cin >>n;
cout << " Number n is " << n << endl;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n){
double sqrt_of_n = sqrt(n);
for (int i =2; i <= sqrt_of_n; ++i){
if (prime (i)){
if (n % i == 0){
cout << i << ", ";
get_divisors(n / i);
return;
}
}
}
cout << n;
}
bool prime (int n){
double sqrt_of_n = sqrt (n);
for (int i = 2; i <= sqrt_of_n; ++i){
if ( n % i == 0) return 0;
}
return 1;
}
I hope someone can help me with this.
You can use an std::unordered_map<int, int> to store two numbers (x and n for x^n). Basically, factorize the number normally by looping through prime numbers smaller than the number itself, dividing the number by the each prime as many times as possible, and recording each prime you divide by. Each time you divide by a prime number p, increment the counter at map[p].
I've put together a sample implementation, from some old code I had. It asks for a number and factorizes it, displaying everything in x^n.
#include <iostream>
#include <unordered_map>
#include <cmath>
bool isPrime(const int& x) {
if (x < 3 || x % 2 == 0) {
return x == 2;
} else {
for (int i = 3; i < (int) (std::pow(x, 0.5) + 2); i += 2) {
if (x % i == 0) {
return false;
}
}
return true;
}
}
std::unordered_map<int, int> prime_factorize(const int &x) {
int currentX = abs(x);
if (isPrime(currentX) || currentX < 4) {
return {{currentX, 1}};
}
std::unordered_map<int, int> primeFactors = {};
while (currentX % 2 == 0) {
if (primeFactors.find(2) != primeFactors.end()) {
primeFactors[2]++;
} else {
primeFactors[2] = 1;
}
currentX /= 2;
}
for (int i = 3; i <= currentX; i += 2) {
if (isPrime(i)) {
while (currentX % i == 0) {
if (primeFactors.find(i) != primeFactors.end()) {
primeFactors[i]++;
} else {
primeFactors[i] = 1;
}
currentX /= i;
}
}
}
return primeFactors;
}
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
auto factors = prime_factorize(x);
std::cout << x << " = ";
for (auto p : factors) {
std::cout << "(" << p.first << " ^ " << p.second << ")";
}
}
Sample output:
Enter a number: 1238
1238 = (619 ^ 1)(2 ^ 1)
To begin with, avoid using namespace std at the top of your program. Second, don't use function declarations when you can put your definitions before the use of those functions (but this may be a matter of preference).
When finding primes, I'd divide the number by 2, then by 3, and so on. I can also try with 4, but I'll never be able to divide by 4 if 2 was a divisor, so non primes are automatically skipped.
This is a possible solution:
#include <iostream>
int main(void)
{
int n = 3 * 5 * 5 * 262417;
bool first = true;
int i = 2;
int count = 0;
while (i > 1) {
if (n % i == 0) {
n /= i;
++count;
}
else {
if (count > 0) {
if (!first)
std::cout << ", ";
std::cout << i;
if (count > 1)
std::cout << "^" << count;
first = false;
count = 0;
}
i++;
if (i * i > n)
i = n;
}
}
std::cout << "\n";
return 0;
}
Note the i * i > n which is an alternative to the sqrt() you are using.
I am trying to do an exercise with the Fibonacci series.
I have to implement with a recursive function, a succession of the prime n number of Fibonacci and print them
in the same function. The problem is that my function print also the intermediate number.
The results, for example, for n = 6, should be : 1 1 2 3 5 8.
Any solutions?
Thanks
#include<iostream>
using namespace std;
int rec(int n)
{
int a, b;
if (n == 0 || n == 1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
cout << a + b << endl;
return a + b;
}
}
int main()
{
int n = 6;
rec(n);
return 0;
}
I have taken help of static int. That worked the way you wanted.
void rec(int n)
{
static int a=0,b=1,sum;
if(n>0)
{
sum = a+b;
a=b;
b= sum;
cout<<sum<<" ";
rec(n-1);
}
}
Though you have to print the first Fibonacci number yourself in main().
cout<<"0 ";
rec(n);
You can use this:
#include<iostream>
using namespace std;
#define MAXN 100
int visited[MAXN];
int rec(int n)
{
if(visited[n])
{
return visited[n];
}
int a, b;
if (n == 0|| n==1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
cout << " " <<a + b;
return visited[n] = a + b;
}
}
int main()
{
int n = 6;
cout<< "1";
rec(n);
cout<<endl;
return 0;
}
This implementation uses dynamic programming. So it reduces the computation time :)
Because you are printing in rec, its printing multiple times because of recursion. No need to print in the recursive function. Instead print the result in main
#include<iostream>
using namespace std;
int rec(int n)
{
int a, b;
if (n == 0 || n == 1)
{
return n;
}
else
{
a = rec(n - 1);
b = rec(n - 2);
//cout << a + b << endl;
return a + b;
}
}
int main()
{
int n = 6;
for (int i = 1; i <= n; i++)
{
cout << rec(i) << endl;
}
system("pause");
return 0;
}
I'm pretty sure you have gotten working solutions but I have a slightly different approach that doesn't require you to use data structures:
/* Author: Eric Gitangu
Date: 07/29/2015
This program spits out the fibionacci sequence for the range of 32-bit numbers
Assumption: all values are +ve ; thus unsigned int works here
*/
#include <iostream>
#include <math.h>
#define N pow(2.0,31.0)
using namespace std;
void fibionacci(unsigned int &fib, unsigned int &prevfib){
unsigned int temp = prevfib;
prevfib = fib;
fib += temp;
}
void main(){
int count = 0;
unsigned int fib = 0u, prev = 1u;
while(fib < N){
if( fib ==0 ){
fib = 0;
cout<<" "<< fib++ <<" \n ";
continue;
}
if( fib == 1 && count++ < 2 ){
fib = 1;
cout<< fib <<" \n ";
continue;
}
fibionacci(fib, prev);
cout<< fib <<" \n ";
}
}
Try this recursive function.
int fib(int n)
return n<=2 ? n : fib(n-1) + fib(n-2);
It is the most elegant solution I know.
I've tried to solve a coin change problem in such a way that it'll compute the minimum numbers of coins that can be used. I've used the algorithm post on http://www.algorithmist.com. Here's the algorithm:
C(N,m) = min(C(N,m - 1),C(N - Sm,m) + 1)
with the base cases:
C(N,m) = 1,N = 0
C(N,m) = 0,N < 0
C(N, m) = 0, N >= 1, m <= 0
But when I write the code it run to infinity.
Here's the code:
#include <iostream>
#include <algorithm>
using namespace std;
int Types[101];
int Coins(int N, int m)
{
if(N==0)
{
return 1;
}
else if(N<0)
{
return 0;
}
else if(N>0 && m<=0)
{
return 0;
}
else
{
int a = Coins(N,m-1);
int b = Coins(N-Types[m],m) + 1;
int c = min(a,b);
return c;
}
}
int main()
{
int noOfCoins, Target;
cin >> noOfCoins >> Target;
for(int i = 0; i<noOfCoins; i++)
{
cin >> Types[i];
}
cout << Coins(Target, noOfCoins);
return 0;
}
What can be wrong?
It should be cout << Coins(Target, noOfCoins - 1);
instead of cout << Coins(Target, noOfCoins);
Otherwise you are accessing a 0 element, and go to the same state again and again here:
int b = Coins(N-Types[m],m) + 1;