Fibonacci numbers - dynamic array - c++

I want to write Fibonacci number program, using dynamic array in function. If I want to initialize array in the function, where I must delete this array? Here is code:
#include <iostream>
using namespace std;
int* fibo(int);
int main()
{
int *fibonacci, n;
cout << "Enter how many fibonacci numbers you want to print: ";
cin >> n;
fibonacci = fibo(n);
for (int i = 0; i<n; i++)
cout << fibonacci[i] << " ";
//for (int i = 0; i < n; i++)
//delete w_fibo[i];
//delete[] w_fibo;
return 0;
}
int* fibo(int n)
{
int* w_fibo = new int[n];
if (n >= 0)
w_fibo[0] = 1;
if (n >= 1)
w_fibo[1] = 1;
for (int i = 1; i < n; i++)
w_fibo[i + 1] = w_fibo[i] + w_fibo[i - 1];
return w_fibo;
}

You don't have to initialize the array! a better dynamic Fibonacci presentation could be like this:
int fib2 (int n) {
int i = 1, j = 0;
for (int k = 0; k < n; k++) { // The loop begins to work real after one loop (k == 1). Sounds interesting!
j += i; // Adds the produced number to the last member of the sequence and makes a new sentence.
i = j - i; // Produces the number that should be added to the sequence.
}
return j;
}
and you can get the n-th fib number using this method. It's O(log(n)) so it's so efficient.`
int fib3 (int n) {
int i = 1, j = 0, k = 0, h = 1, t=0;
while (n > 0) {
if (n % 2) { // |
t = j * h; // |
j = i * h + j * k + t;
i = i * k + t;
}
t = h * h;
h = 2 * k * h + t;
k = k * k + t;
n /= 2;
}
return j;
}

If you allocate a std::vector<int> inside fibo() and reserve enough memory, and then return it by value, the memory allocation is taken care for you by the compiler:
#include <iostream>
#include <vector>
using namespace std;
std::vector<int> fibo(int n)
{
std::vector<int> w_fibo;
w_fibo.reserve(n);
if (n >= 0)
w_fibo[0] = 1;
if (n >= 1)
w_fibo[1] = 1;
for (int i = 1; i < n; i++)
w_fibo[i + 1] = w_fibo[i] + w_fibo[i - 1];
return w_fibo;
}
int main()
{
int n = 10;
std::vector<int> fibonacci = fibo(n);
for (int i = 0; i<n; i++)
cout << fibonacci[i] << " ";
}
Live Example.
NOTE: This is guaranteed to avoid needlessly copying in C++11 (move semantics) and is likely to do so in C++98 (copy-elision using the return-value-optimization).

This is an old question, but just in case someone happens to pass by this might be helpful.
If you need a efficient method to get the nth Fibonacci number, we have a O(1) time complexity procedure.
It is based on Binet's formula, which I think our friends over at math.se will be better at proving, so feel free to follow that link.
The formula itself is, given a=1.618 and b=-0.618 (these are approximate values)
the n-th term is (a^n - b^n)/2.236. A good way to round that off(since we are using approximate values) would be adding 0.5 and taking the floor function.
math.floor(((math.pow(1.618,n)-math.pow(-0.618,n))/2.236 + 0.5)

Related

Reducing Algorithm Time Complexity of Recursive Function

This is the code for function f(T,k) where
f(T,0)=∑(from i=1 to i≤len(T)) T[i], where len(T) is length of array T.
f(T,k)=∑(from i=1 to i≤len(T)) ∑(from j=i to j≤len(T)) f(T[i...j],k-1), for k>0, where len(T) is length
of array T and T[i...j] is sub-array of T with elements form the i-th to the j-th position (T[i],T[i+1],...,T[j])
It is a recursive function and I need to reduce the complexity, but I don't know how.
Can someone help me out?
This is the problem text:
1000000007 players participate in this game and the winner is decided by random selection. To make the selection random, the company has set strict rules for selecting that player. First they number the players with identification numbers from 0 to 1000000006. Then they choose array A with N elements and the number k. They then define the winner as the player who has the identification number f (A, k) mod (100000007)
#include <iostream>
#include <vector>
using namespace std;
int N,k,a;
vector<int>A;
int fja(vector<int>A,int k){
long long suma=0;
if(k==0){// If k==0 calculate the first said function
for(auto it=A.begin();it!=A.end();it++)suma=(suma+(*it))%(1000000007);//Moduo is there because suma is very big
return suma;
}else{//If k>0 calculate the second function
int duzina=A.size();//duzina is length of A (T)
for(int i=0;i<duzina;i++){//Going through the first and second sum of second function
for(int j=i;j<duzina;j++){
vector<int>b(A.begin()+i,A.begin()+j+1);//Creating new vector (array) to pass it into the new function call
suma=(suma+fja(b,k-1))%(1000000007);//Moduo is there because suma is very big
}
}
return suma;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>N>>k; //Number of elements and k
for(int i=0;i<N;i++){
cin>>a;
A.push_back(a);//All the elements
}
cout<<fja(A,k);
}
I implemented non-recursive version, only loop-based, but it has O(k * n^4) so for biggest 10^5 values of N and k it will be too slow.
I provided recursive solution for reference, it can solve for N and k up to 10, my non-recursive solution can solve up to N and k of 100.
I'm sure some loops can be removed in my solution by algorithmic optimization. Still I could not figure out how to solve task for very large values of 10^5.
In current main() function N and k both are 10, for testing only, to leave only fast version you may change N and k from 10 to 100 and comment out f_ref() call. f_ref() is reference recursive function, f_fast() is my faster variant.
Try it online!
#include <cstdint>
#include <vector>
#include <iostream>
typedef uint32_t u32;
typedef int64_t i64;
typedef uint64_t u64;
enum { mod = 100000007 };
i64 f_ref(std::vector<i64> const & T, size_t begin, size_t end, size_t k) {
i64 sum = 0;
if (k == 0)
for (size_t i = begin; i < end; ++i)
sum = (sum + T[i]) % mod;
else
for (size_t i = begin; i < end; ++i)
for (size_t j = i; j < end; ++j)
sum = (sum + f_ref(T, i, j + 1, k - 1)) % mod;
return sum;
}
i64 f_fast(std::vector<i64> const & T, size_t k) {
size_t N = T.size();
std::vector<std::vector<i64>> mc, mn;
for (size_t n = 1; n <= N; ++n) {
mc.resize(mc.size() + 1);
for (size_t j = 0; j < n; ++j)
mc.back().push_back(((n + (n - 2 * j)) * (j + 1) / 2) % mod);
}
for (size_t ik = 0; ik + 1 < k; ++ik) {
mn.clear();
mn.resize(N);
for (size_t n = 1; n <= N; ++n) {
mn[n - 1].resize(n);
for (size_t i = 0; i < n; ++i)
for (size_t j = i; j < n; ++j)
for (size_t l = 0; l <= j - i; ++l)
mn[n - 1][i + l] = (mn[n - 1][i + l] + mc[j - i][l]) % mod;
}
mc = mn;
}
i64 sum = 0;
for (size_t i = 0; i < N; ++i)
sum = (sum + mc.back()[i] * (T[i] % mod)) % mod;
return sum;
}
int main() {
std::vector<i64> a;
for (size_t i = 0; i < 10; ++i)
a.push_back(i + 1);
size_t k = 10;
std::cout << f_ref(a, 0, a.size(), k) << " " << f_fast(a, k) << std::endl;
return 0;
}
Output for N = 10 and k = 10:
78689325 78689325
Output for N = 100 and k = 100:
37190121

prime seive algorithm giving a runtime error

I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}

Function to find the smallest prime x and the biggest m = power_of(x) such that n % m = 0 and n % x = 0?

Given m integer from 1 to m, for each 1 <=i <= m find the smallest prime x that i % x = 0 and the biggest number y which is a power of x such that i % y = 0
My main approach is :
I use Eratos agorithm to find x for every single m like this :
I use set for more convenient track
#include<bits/stdc++.h>
using namespace std;
set<int> s;
void Eratos() {
while(!s.empty()) {
int prime = *s.begin();
s.erase(prime);
X[prime] = prime;
for(int j = prime * 2; j <= L ; j++) {
if(s.count(j)) {
int P = j / prime;
if( P % prime == 0) Y[j] = Y[P]*prime;
else Y[j] = prime;
}
}
}
signed main() {
for(int i = 2; i<= m; i++) s.insert(i);
Eratos();
for(int i = 1; i <= m; i++) cout << X[m] << " " << Y[m] ;
}
with X[m] is the number x corresponding to m and same as Y[m]
But it seems not really quick and optimal solution. And the memory request for this is so big and when m is 1000000. I get MLE. So is there an function that can help to solve this problem please. Thank you so much.
Instead of simply marking a number prime/not-prime in the original Sieve of Eratosthenes, save the corresponding smallest prime factor which divides that number.
Once that's done, the biggest power of the smallest prime of a number would mean to simply check how many times that smallest prime appears in the prime factorization of that number which is what the nested for loop does in the following code:
#include <iostream>
#include <vector>
using namespace std;
void SoE(vector<int>& sieve)
{
for (int i = 2; i < sieve.size(); i += 2)
sieve[i] = 2;
for (int i = 3; i < sieve.size(); i += 2)
if (sieve[i] == 0)
for (int j = i; j < sieve.size(); j += i)
if(sieve[j] == 0)
sieve[j] = i;
}
int main()
{
int m;
cin >> m;
vector<int> sieve(m + 1, 0);
SoE(sieve);
for (int i = 2; i < sieve.size(); ++i)
{
int x, y;
x = y = sieve[i];
for (int j = i; sieve[j / x] == x; j /= x)
y *= x;
cout << x << ' ' << y << endl;
}
}
I didn't get what you're trying to do but I understand that you're trying to use Sieve of Eratosthenes to find prime numbers. Well, what you probably need is a bitset, it's like a boolean array but uses bits instead of bytes which means it uses less memory. Here's what I did:
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
vector<int> primes;
int main()
{
const int m = 1e7;
bitset<m> bs;
int limit = (int) sqrt (m);
for (int i = 2; i < limit; i++) {
if (!bs[i]) {
for (int j = i * i; j < m; j += i)
bs[j] = 1;
}
}
for (int i = 2; i < m; i++) {
if (!bs[i]) {
primes.push_back (i);
}
}
return 0;
}

Range max sum query using sparse table

I Implemented range max sum query using sparse Table ,I Know more efficient approach would be using segment trees.
What I have tried:
I am calculating the max sum in the range (i,2^j-1) for all possible value of i and j and storing them in a table
where i is the index and j denotes the power of 2 (2^j denotes the length of segment from i for which we are calculating max sum)
Now using the above table we can answer the queries
Input:
3
-1 2 3
1
1 2
expected output:
2
actual output:
"wrong answer(garbage value)"
we actually have to tell the max contiguous sum in a given query
Link to the ques spoj gss1
Please help:
#include<iostream>
#include<vector>
#include<algorithm>
#include<climits>
using namespace std;
const int k = 16;
const int N = 1e5;
const int ZERO = 0; // ZERO + x = x + ZERO = x (for any x)
long long table[N][k + 1]; // k + 1 because we need to access table[r][k]
long long Arr[N];
int main()
{
int n, L, R, q;
cin >> n; // array size
for(int i = 0; i < n; i++)
cin >> Arr[i];
// build Sparse Table
for(int i = 0; i < n; i++)
table[i][0] = Arr[i];
for(int j = 1; j <= k; j++) {
for(int i = 0; i <= n - (1 << j); i++)
//table[i][j] = table[i][j - 1] + table[i + (1 << (j - 1))][j - 1];
table[i][j] = max(table[i][j-1],max(table[i+(1<<(j-1))][j-1],table[i+(1<<(j-1))][j-1]+table[i][j-1]));
}
cin >> q; // number of queries
for(int i = 0; i < q; i++) {
cin >> L >> R; // boundaries of next query, 0-indexed
long long int answer = LLONG_MIN;
for(int j = k; j >= 0; j--) {
if(L + (1 << j) - 1 <= R) {
answer = max(answer,answer + table[L][j]);
L += 1 << j; // instead of having L', we increment L directly
}
}
cout << answer << endl;
}
return 0;
}
link to the question Spoj Gss1

Generating all R-digit numbers among N digits in C++ (combinations, iterative)?

I have a program, where I have to generate all R-digit numbers among N digits in C++, for example for N=3 (all digits from 1 to N inclusive) and R=2 the program should generate 12 13 21 23 31 32. I tried to do this with arrays as follows, but it does not seem to work correctly.
#define nmax 20
#include <iostream>
using namespace std;
int n, r;
void print(int[]);
int main()
{
cin >> n;
cin >> r;
int a[nmax];
int b[nmax];
int used[nmax];
for (int p = 1; p <= n; p++) {
//Filling the a[] array with numbers from 1 to n
a[p] = n;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < r; j++) {
b[j] = a[i];
used[j] = 1;
if (used[j]) {
b[j] = a[i + 1];
}
used[j] = 0;
}
print(b);
}
return 0;
}
void print(int k[]) {
for (int i = 0; i < r; i++) {
cout << k[i];
}
}
If I understand your question correctly, you can explore this website where it explains the problem and suggests the solution thoroughly.
Here is a slightly altered code:
Pay attention that time is an issue for bigger N values.
#define N 5 // number of elements to permute. Let N > 2
#include <iostream>
using namespace std;
// NOTICE: Original Copyright 1991-2010, Phillip Paul Fuchs
void PrintPerm(unsigned int *a, unsigned int j, unsigned int i){
for(unsigned int x = 0; x < N; x++)
cout << " " << a[x];
cout << " swapped( " << j << " , " << i << " )\n";
}
void QuickPerm(void){
unsigned int a[N], p[N+1];
register unsigned int i, j, PermCounter = 1; // Upper Index i; Lower Index j
for(i = 0; i < N; i++){ // initialize arrays; a[N] can be any type
a[i] = i + 1; // a[i] value is not revealed and can be arbitrary
p[i] = i;
}
p[N] = N; // p[N] > 0 controls iteration and the index boundary for i
PrintPerm(a, 0, 0); // remove comment to PrintPerm array a[]
i = 1; // setup first swap points to be 1 and 0 respectively (i & j)
while(i < N){
p[i]--; // decrease index "weight" for i by one
j = i % 2 * p[i]; // IF i is odd then j = p[i] otherwise j = 0
swap(a[i], a[j]); // swap(a[j], a[i])
PrintPerm(a, j, i); // remove comment to PrintPerm target array a[]
PermCounter++;
i = 1; // reset index i to 1 (assumed)
while (!p[i]) { // while (p[i] == 0)
p[i] = i; // reset p[i] zero value
i++; // set new index value for i (increase by one)
} // while(!p[i])
} // while(i < N)
cout << "\n\n ---> " << PermCounter << " permutations. \n\n\n";
} // QuickPerm()
int main(){
QuickPerm();
} //main
Here is a list of the modified items from the original code.
N defined to be 5 instead of 12.
A Counter has been added for more informative result.
The original swap instructions reduced by using c++ standard libraries' swap() function.
The getch() has been removed.
The 'Display()' function has been renamed to be 'PrintPerm()'.
The printf() function has been replaced by cout.
Printing number of permutation has been added.