2 to the power 2 n times incorrect - c++

Please tell me what is wrong, the output is wrong, shows 4 to me
F​1​ = 2, F​n​ = (F​n-1​)​
2​ , n ≥ 2
i. What is the complexity of the algorithm that computes ​F​n
using the recursive
definition given above.
#include <iostream>
using namespace std;
double calcFn(double,int);
int main()
{
cout << calcFn(2, 4);
cout << endl;
cin.get();
return 0;
}
double calcFn(double F1, int N)
{
cout << endl;
double Fn = F1 * F1;
while (N > 0)
{
N--;
calcFn(Fn, N);
}
return Fn;
}
// CODE DOESNT SHOW the RIGHT oUTPUT

First of all, You have recurrency, so you should not use the loop. Secondly, You do not assign return value. The corrected snippet:
if (N > 0)
{
N--;
Fn = calcFn(Fn, N);
}
Still, I'm not sure about the result, but You can further correct it.

Related

Code runs but shows no output after inputting a value [closed]

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 3 years ago.
Improve this question
I'm trying to implement dp on a fibonacci sequence using vector.If i declare memo globally as an array with given size it runs fine.But while using vector it shows no output on the console.
What seems to be the problem here?
#include<bits/stdc++.h>
using namespace std;
int fib(int n)
{
vector<int>memo;
int f;
if(memo[n]!=0)
return memo[n];
if(n<=2)
return 1;
else
f = fib(n-1)+fib(n-2);
memo.push_back(f);
return f;
}
int main()
{
int num;
cin>>num;
cout<<fib(num);
}
The problem here is your declaration of memo:
vector<int>memo;
It is not static, and thus goes out of scope every time the function exits. However, you seem to expect it to still be in scope when the function exits.
Thus, make it static:
static vector<int>memo;
Side note: I would check that n is less than memo.size() before trying to do something like if(memo[n]!=0), because if n is greater than the size, then I believe this is undefined behavior.
Side note 2: You shouldn't include bits/stdC++.h
Here's the corrected code.
#include <iostream>
#include <vector>
using namespace std;
int fib (int n)
{
static vector<int>memo = {1, 1}; // should be static. also init it.
int f;
if (n < memo.size () && memo [n] != 0) // check the size of vector before accessing
return memo [n];
if (n <= 2)
return 1;
else
f = fib (n - 2) + fib (n - 1); // n-2 should be found and inserted before n-1
memo.push_back (f);
return f;
}
int main ()
{
int num;
cin >> num;
cout << fib (num);
}
There were three main issues with the code.
memo should have been declared as static. Previously with each call to fib(), it was creating a fresh 'memo' variable.
memo[n]!=0 might cause a segfault since the vector could be small. You should check the size before referencing nth item.
You were pushing the n'th value to (n-2)'th place. So let's first initialize the vector with {1,1}
Now the series will be generated as...
1 1 2 5 8 13 21 34 55
There are some problems in your code:
You are not allocating space on memo and this is why you get no output.
memo must be static so it lives over the recursion and you can get real memoization
You are using memo.push_back(f);. This defeats memoization because the indices will not correspond to what you want to find in memo
Fixing these issues leads to a code like this:
#include<iostream>
#include<vector>
using namespace std;
int fib(int n)
{
static vector<int> memo(n + 1, 0);
if (n > memo.capacity() - 1)
memo.resize(n + 1, 0);
int f;
if(memo[n]!=0)
return memo[n];
if(n<=2)
return 1;
else
f = fib(n-1)+fib(n-2);
memo[n] = f;
return f;
}
int main()
{
int num;
cin >> num;
cout << fib(num) << endl;
}
The reason nothing is shoring it is the program is running, but you don't know. Change to this it will show.
cout << "Enter a number : ";
cin >> num;
because you are using recursive, in the fib() function, you create memo multiple times. This will return "program terminated with signal 11 segmentation fault"
When you first call fib(), there's nothing in the memo, so you cannot do memo[n].
Hope this helps.
I figured it out.
I changed the checking statement
if(memo[n]!=0)
to this if(!memo.empty()).
And the rest are all the same.
This approach - recursion with memoization - is much easier with a map:
#include <iostream>
#include <map>
using namespace std;
int fib(int n) {
static map<int, int> memo; #pairs are n, f
int f = 0;
if (memo.count(n) > 0)
return memo.at(n);
if (n <= 2 )
return 1;
else
f = fib(n - 1) + fib(n - 2);
memo.emplace(n, f);
// cout << n << " " << f << endl; #run this with and w/o 'static' to see effect
return f;
}
int main() {
for (int i = 1, i < 12, i++)
cout << fib(i) << " ";
cout << endl;
}
gives:
1 1 2 3 5 8 13 21 34 55 89
[Edit] : Here's the vector version, it needed this loop inside however:
int fibVec(int n) {
static vector<int> memo;
int f = 0;
for (int i = 0; i < memo.size(); i++) { //search the vector by index
if (i == n)
return memo[i];
}
if (n <= 2 )
return 1;
else
f = fib(n - 1) + fib(n - 2);
memo.push_back(f);
return f;
}

When i recurse the following code on function prime the program crashes what is wrong in my code?

Whenever I try to recurse in the function prime, my program crashes at that step. I think the problem is passing the function small as a recursion. What am I doing wrong?
#include <iostream>
using namespace std;
int smallest(int n) {
for( int x = 2 ; x <= n/2 ; x++){
if (n%x==0) {
return x;
}
else {
return 0;
}
}
}
int prime(int n, int(*small)(int)) {
int factor;
if (n == 1){
return 0;
}
else {
factor = n % small(n);
cout << small(n) << endl;
return prime(factor , small);
}
}
int main() {
prime(50 , &smallest);
return 0;
}
As the comments point out, when small returns 0, you continue recursing when you shouldn't. This can be solved with a small update to your base case:
if (n <= 1){
return 0 ;
}
Furthermore, it's worth pointing out that as it stands, your prime function will never call itself more than once. When you call smallest, you are guaranteed to get a prime number!

Sum of factoriais to be equal a given number

I'm trying to solve the following problem:
What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)
Example:
Input: 10, Output: 3. (10 = 3! + 2! + 2!)
Input: 25, Output: 2. (25 = 4! + 1!)
My code:
#include<bits/stdc++.h>
using namespace std;
int a;
int rec(int vet){
int count = 0;
a = a - vet;
if(a >= vet){
count++;
rec(vet);
}
count++;
return count;
}
int main(){
int vet[8] = {1}, count = 0;
cin >> a;
for(int i = 2; i <= 8; i++){
vet[i-1] = vet[i-2]*i;
}
for(int i = 7; i >= 0; i--){
if(a < vet[i]){
continue;
}
count += rec(vet[i]);
}
cout << count << endl;
}
My logic:
1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;
2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.
This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.
Can you find where am I wrong? Or if my solution is not good and I should try another approach.
Thanks for the help!
The problem is easily solved by a recursive approach.
Here is checked code:
#include <iostream>
using namespace std;
int factorial(int n) {
return n<=1 ? 1 : n * factorial(n-1);
}
int MinFact(int number)
{
static int num_of_facts;
int a = 1;
if (number)
{
while(factorial(a+1)<=number)a++;
cout << a << "!" << endl;
num_of_facts++;
MinFact((number-factorial(a)));
}
return num_of_facts;
}
int main()
{
int num;
cout << "Enter number" << endl;
cin >> num;
num = MinFact(num);
cout << "Number of factorials: " << num;
return 0;
}
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.
A simple solution would be to replace the rec function as follows
int rec(int vec) {
int count = a / vec;
a = a % vec;
return count;
}
Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.

putting different values in return statement of c++

// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1){
return (a * factorial (a-1)); }//function calling itsself
else
return 0;
}
main ()
{
long number = 2;
cout << number << "! = " << factorial (number);
}
i am begginer learning objects and classes. i get some code from my context but its getting some error.
how return statement is working when its value is 0 out put becomes 0 when it is return 1 output is 2. when it is return 3 output is 6 similar for 4 is 8.
Here's a calculator to compute factorial
#include <iostream>
using namespace std;
int Factorial(int long long a) {
int long long Ans = 1;
for (int x = 1; x <= a; x++) {
Ans *= x;
}
return Ans;
}
int main() {
int Input;
cin >> Input;
if (Input > 0) {
cout << Factorial(Input);
}
}
Calling a function from within itself is generally considered bad practice, so avoid it. Use long long if you need larger numbers. Also, try to provide more information about your question.

Whats wrong with my Prime number Checker?

I created a prime number checking program which checks the user entered number prime or not.
It detects non prime numbers easily, but when we type prime numbers, it crashes!
I think I know why, but don't know how to rectify them...
Here's my Program:
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
Remainder(n, x + 1 > n);
/*
Here is the PROBLEM
*/
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n = Asker();
int r = Remainder(n, 2);
if (r == 1)
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
main();
return 0;
}
Suppose, when I enter 7, I know that, it checks upto 6, then it should crash!(due to x + 1 > n condition). I don't know how to return 0 when it fails the else condition...
To answer to your question "Whats wrong with my Prime number Checker?" a lot of things are wrong:
Don't call main() in main. That's not how you do recursion
int Remainder(int n, int x) and you call it with a float (cast is missing) then with a bool : Remainder(n, x + 1 > n);
Your asker doesn't need to be a float
About the recursion within main there is two reason:
With this config you'll get an endless loop;
ISO C++ forbids taking address of function '::main'
//#include "stdafx.h" //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0 && n>2 )//'2' have to be excluded.
//otherwise 2%2==0 can set
//'2' as a non prime which is wrong
return 1;
else if(x+1<n)
Remainder(n, x + 1);
/*
Here was the PROBLEM
Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
*/
else
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n=Asker();
int r=1; //It is essential to initialize r to 1
if(n!=1) //Have to exclude '1'. Otherwise
//It will assign '1' as prime which is wrong
r = Remainder(n, 2);
if (r == 1 )
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
//main(); //Why are you calling main again?
return 0;
}
Your first error was " #include "stdafx.h" ". Where'd you get this header?
Then inside int Remainder(int n, int x) function you used recursion and sent an invalid syntax " Remainder(n, x + 1 > n) ". You can't use syntax like x+1>n in a parameter.
After that why are you calling main() inside main function?
And your algorithm needed some touch which I have added and explained in comment.
But you should know that the shortest way to check a prime number is to check n%x==0 till x<=square_root(n).
First of all you don't have to check modulo for all numbers up to n-1: it is sufficient to check modulo up to sqrt(n). Second, you should return 0 from the function if the next divisor to check is larger than sqrt(n). Here is the corrected Remainder function.
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
{
if(x+1 > std::sqrt(n)) return 0;
else return Remainder(n, x + 1);
}
}
Finally, it is better to change the type of n in main and Asker from float to int, and return type of Asker should be int too.
This is not an exhausting list of what's wrong with the prime number checker in focus - just a way to fix it quickly. Essentially, such prime number checker shouldn't use recursion - it's more neat to just iterate over all potential divisors from 2 to sqrt(n).