C++ Fibonacci Program - c++

C++ Program help
Hello, I am writing a c++ program to print out several fibonacci numbers that are prime. The program prints out 8 numbers but not only those that are prime. Can some please help me find out what is going on
#include <iostream>
#include <cmath>
using namespace std;
//fibonacci function
int fibonacci(int x) {
if ((x == 1) || (x == 2)) { return 1; }
return fib(x - 1) + fib(x - 2);
}
//prime test bool function
bool is_prime(double n) {
for (int i = 2; i <= sqrt(n); i++) {
if (n % i != 0) { return true; }
else { return false; }
}
}
// main function
int main (){
int y = 1;
int c = 0;
while (y >= 0) {
fibonacci(y);
if ((is_prime(true)) && (fibonacci(y) != 1)) {
cout << fib(y) << " ";
count++;
if (c >= 8) { return 0; }
}
y++;
}
}
return 0;
}

Your code above uses double names for the function, and also you use c while you may mean count.
The is_prime function logic should take an int and the function logic is better to be rewritten to look for values that show if the number is not prime.
Lastly, using recursion with Fibonacci function is resource exhaustive. it is better to use plain loops.
check this code against yours:
#include <iostream>
#include <cmath>
using namespace std;
int fib(int x)
{
int first = 0, second = 1, sum = 0;
if ((x == 1) || (x == 2)) { return 1; }
for (int i = 2; i <= x; ++i)
{
sum = first + second;
first = second;
second = sum;
}
return sum;
}
bool is_prime(int n) // n should be int not double
{
for (int i = 2; i <= sqrt(n); i++)
if (n % i == 0)
return false; // you should look for what breaks the condition
return true; // if nothing break the condition you return true
}
int main ()
{
for (int i = 1; i <= 8; ++i)
{
int f = fib(i);
if (is_prime(f))
cout << f << " ";
}
}

Your is_prime() function has a logical problem and appears to be returning the opposite evaluation for input numbers. Try the following:
bool is_prime(int n) {
for (int i=2; i <= sqrt(n); i++) {
// if input divisible by something other than 1 and itself
// then it is NOT prime
if (n % i == 0) {
return false;
}
}
// otherwise it is prime
return true;
}
Here is a demo showing that the refactored is_prime() function is working correctly:
Rextester
Then you can use this function along with your Fibonacci number generator to find say the first 8 prime Fibonacci numbers:
int c = 0;
int y = 1;
do {
int fib = fibonacci(y);
++y;
if (is_prime(fib)) {
cout << fib << " ";
++c;
}
} while (c < 8);
As a side note, your fibonacci() function uses recursion and it won't scale well for large number inputs. Consider using dynamic programming there to dramatically improve performance.

Use Tim Biegeleisen answer for the issues in is_prime() function.
But additionally you do not check your Fibonacci number at all, is_prime is always being called with the same value is_prime(true). And apart of that, in current implementation while cycle will never finish. Try to consider following for the while loop:
while (y >= 0) {
double fib = fibonacci(y);
if ( is_prime(fib) && (fib != 1) ) {
cout << fib << " ";
c++;
if (c >= 8) { return 0; }
}
y++;
}

Related

Breaking out of loop from function after printing the last prime number of a given range

I'm writing a code to find the last prime number of a given range. Suppose the range is 1 to 50. Then the last prime no. I want to print must be 47. My idea was to maybe reverse the order of prime numbers in the range and then try printing only the first value. Again kinda like if my order was 1 to 50 then I would start printing from 47, 43 and so on and only print 47. But I'm stuck and not getting ideas on how I could do this. here's my code
int prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
}
return 0;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
prime_bef(i);
}
return 0;
}
You can just use exit() in the place you want to end the program, and it works fine in your case. But by far the best approach is returning a value to test for continuation, it is the most readable.
#include<iostream>
#include <stdlib.h>
using namespace std;
int prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
exit(0);
}
return 0;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
prime_bef(i);
}
return 0;
}
Same code using bool return type:
#include<iostream>
using namespace std;
bool prime_bef(int n)
{
int check = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
check++;
}
}
if (check == 2)
{
cout << n << " ";
return true;
}
return false;
}
int main ()
{
int l;
int u;
cin >> l >> u;
for (int i = u; i >= l; i--)
{
if(prime_bef(i))
break;
}
return 0;
}
Here is a simple and efficient way to check if the number is prime. I am checking if the number is prime and when it is true I am printing the number and breaking the loop so that only 1 number is printed. You can always remove the break statement and print all prime numbers in range.
#include<iostream>
using namespace std;
bool isPrime(int n){
if(n==2)return true;
if(n%2==0 || n==1)return false;
for(int i=3; i*i<=n; ++i){
if(n%i==0){
return false;
}
}
return true;
}
int main (){
int l, u;
cin>>l>>u;
for (int i = u; i >= l; i--){
if(isPrime(i)){
cout<<i<<"\n";
break;
}
}
return 0;
}
I'll give you a hint... while you are iteratively checking for the prime nature of the number, also check whether the last prime number calculated in the loop is greater than the max term of the range and break the loop when the condition becomes false.
Here a C++17 approach :
#include <cmath>
#include <iostream>
#include <vector>
// type to use for storing primes
using prime_t = unsigned long;
// there is a way to determine an upper bound to the number of primes smaller then a maximum number.
// See : https://primes.utm.edu/howmany.html
// this can be used to estimate the size of the output buffer (vector)
prime_t pi_n(const prime_t max)
{
prime_t pi_n{ max };
if (max > 10)
{
auto ln_n = std::log(static_cast<double>(max));
auto value = static_cast<double>(max) / (ln_n - 1.0);
pi_n = static_cast<prime_t>(value + 0.5);
}
return pi_n;
}
// Calculate prime numbers smaller then max
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
auto calculate_primes(const prime_t max)
{
std::vector<bool> is_primes(max, true);
// 0, 1 are not primes
is_primes[0] = false;
is_primes[1] = false;
// sieve
for (prime_t n = prime_t{ 2 }; n < prime_t{ max }; ++n)
{
if (is_primes[n])
{
auto n2 = n * n;
for (prime_t m = n2; m < max; m += n)
{
is_primes[m] = false;
}
}
}
// avoid unnecessary resizes of vector by pre-allocating enough entries to hold result
prime_t n{ 0 };
std::vector<prime_t> primes;
primes.reserve(pi_n(max));
// add all prime numbers found by the sieve
for (const auto is_prime : is_primes)
{
if (is_prime) primes.push_back(n);
n++;
}
return primes;
}
int main()
{
const prime_t max{ 50 };
auto primes = calculate_primes(max);
// max prime is last one in container
auto max_prime = primes.back();
std::cout << "maximum prime number smaller then " << max << ", is " << max_prime << std::endl;
}

How to check if a number is prime in a more efficient manner?

So I have the following problem. They give me an array w/ n numbers and I have to print if it contains any prime numbers using "Divide et Impera". I solved the problem but it gets only 70/100 because it isn't efficient(they say).
#include <iostream>
using namespace std;
bool isPrime(int x){
if(x == 2) return false;
for(int i = 2; i <= x/2; ++i)
if(x%i==0) return false;
return true;
}
int existaP(int a[], int li, int ls){
if(li==ls)
if(isPrime(a[li]) == true) return 1;
else return 0;
else return existaP(a, li, (li+ls)/2)+existaP(a, (li+ls)/2+1, ls);
}
int main(){
int n, a[10001];
cin >> n;
for(int i = 1; i<=n; ++i) cin >> a[i];
if(existaP(a,1,n) >= 1) cout << "Y";
else cout << "N";
return 0;
}
The lowest hanging fruit here is your stopping conditional
i <= x/2
which can be replaced with
i * i <= x
having taken care to ensure you don't overflow an int.This is because you only need to go up to the square root of x, rather than half way. Perhaps i <= x / i is better still as that avoids the overflow; albeit at the expense of a division which can be relatively costly on some platforms.
Your algorithm is also defective for x == 2 as you have the incorrect return value. It would be better if you dropped that extra test, as the ensuing loop covers it.
Here is an efficinent way to check prime number.
bool isPrime(int num) {
if(num <= 1) return false;
if (num <= 3) return true;
int range = sqrt(num);
// This is checked so that we can skip
// middle five numbers in below loop
if (num % 2 == 0 || num % 3 == 0)
return false;
for (int i = 5; i <= range; i += 6)
if (num % i == 0 || num % (i + 2) == 0)
return false;
return true;
}
A stander way(maybe..?) is just check from i = 0 to the sqrt(number)
bool isPrime(int num){
if(num == 1) return false;
for(int i = 2;i<=sqrt(num);i++){
if(num % i == 0) return false;
}
return true;
}
bool isprime(int x)
{
if(x <= 1) return false;
if(x == 2 || x == 3) return true;
if(x % 2 == 0 || x % 3 == 0) return false;
if((x - 1) % 6 != 0 && (x + 1) % 6 != 0) return false;
for(int i = 5; i * i <= x; i += 6)
{
if(x % i == 0 || x % (i + 2) == 0) return false;
}
return true;
}
If prime numbers need to be printed for a particular range or to determine whether a number is prime or not, the sieve of the eratosthenes algorithm is probably preferable as it is very efficient in terms of time complexity O( n * log2( log2(n) ) ), but the space complexity of this algorithm can cause an issue if the numbers are exceeding certain memory limit.
We can optimize this simpler algorithm which has a time complexity of O(n1/2) by introducing few additional checks based on this thoerem as shown in the above isprime code block.
Despite the fact that Sieve of Erathosthenes algorithm is efficient in terms of time complexity under space restrictions, the above provided isprime code block can be utilized, and there are numerous variations of the Sieve of Erathosthenes algorithm that perform considerably better, as explained in this link.
Many more algorithms exist, but in terms of solving coding challenges, this one is simpler and more convenient. You can learn more about them by clicking on the following links:
https://www.quora.com/Whats-the-best-algorithm-to-check-if-a-number-is-prime
https://www.baeldung.com/cs/prime-number-algorithms#:~:text=Most%20algorithms%20for%20finding%20prime,test%20or%20Miller%2DRabin%20method.
Your code will give a wrong answer if n is 1.
Your time complexity can be decreased to sqrt(n) , where n is the number.
Here is the code
bool isPrime(long int n)
{
if (n == 1)
{
return false;
}
int i = 2;
while (i*i <= n)
{
if (n % i == 0)
{
return false;
}
i += 1;
}
return true;
}
The "long int" will help to avoid overflow.
Hope this helps. :-)
If the numbers are not too big you could also try to solve this using the sieve of Eratosthenes:
#include <iostream>
#include <array>
using namespace std;
constexpr int LIMIT = 100001;
// not_prime because global variables are initialized with 0
bool not_prime[LIMIT];
void sieve() {
int i, j;
not_prime[2] = false;
for(int i = 2; i < LIMIT; ++i)
if(!not_prime[i])
for(int j = i + i; j < LIMIT; j += i)
not_prime[j] = true;
}
int existaP(int a[], int li, int ls){
if(li==ls)
if(!not_prime[a[li]] == true)
return 1;
else
return 0;
else
return existaP(a, li, (li + ls) / 2) + existaP(a, (li + ls) / 2 + 1, ls);
}
int main(){
int n, a[10001];
cin >> n;
for(int i = 1; i<=n; ++i) cin >> a[i];
sieve();
if(existaP(a,1,n) >= 1) cout << "Y";
else cout << "N";
return 0;
}
Basically when you encounter a prime all the numbers that are a multiple of it won't be primes.
P.S.: Acum am vazut ca esti roman :)
Poti sa te uiti aici pentru a optimiza si mai mult algoritmul: https://infoarena.ro/ciurul-lui-eratostene
Another inefficiency not yet mentioned is existaP(a, li, (li+ls)/2) + existaP(a, (li+ls)/2+1, ls);
In particular, the problem here is the +. If you know existaP(a, li, (li+ls)/2) > 0, then existaP(a, (li+ls)/2+1, ls) no longer matters. In other words, you're currently counting the exact number of unique factors, but as soon as you know a number has at least two factors you know it's not prime.
Here is one efficient way to check a given number is prime.
bool isprime(int n) {
if(n<=1)
return false;
if(n<=3)
return true;
if(n%2==0||n%3==0)
return false;
for(int i=5;i*i<=n;i=i+6) {
if(n%i==0||n%(i+2)==0)
return false;
}
return true;
}
This is a much faster algorithm in my opinion. It works on the Euclidean algorithm to calculate H.C.F. Basically, I check if the HCF of the number AND the consecutively second number is 1; and if the number itself is divisible by either 2 or 3. Don't ask how I mathematically reached the solution, it just struck me :D. The time complexity of this solution is O(log (max(a,b))), which is notably smaller than the time complexity of the program which runs a loop counter 2 to sqrt(n) is O(sqrt(n)).
#include <iostream>
using namespace std;
int hcf(int, int);
int hcf(int a, int b)
{
if (b == 0)
{
return a;
}
return hcf(b, a % b);
}
int main()
{
int a;
cout << "\nEnter a natural number: ";
cin >> a;
if(a<=0)
{
cout << "\nFor conventional reasons we keep the discussion of primes to natural numbers in this program:) (Read: Ring of Integers / Euclid's Lemma)";
return 0;
}
if (a == 1)
{
cout << "\nThe number is neither composite nor prime :D";
return 0;
}
if (a == 2)
{
cout << "\nThe number is the only even Prime :D";
return 0;
}
if (hcf(a, a + 2) == 1)
{
if (a % 2 != 0 && a % 3 != 0)
{
cout << "\nThe number is a Prime :D";
return 0;
}
}
cout << "\nThe number is not a Prime D:";
return 0;
}
Correct me if I'm wrong. I'm a student.

Program to print first 5 perfect numbers, is printing 2096128?? C++

So this program will print perfect numbers, but one of them, 2096128, is being printed for some reason? Would really appreciate some help figuring out what is happening! Thank you! I can't figure out why one non perfect number is finding it way into the sequence!
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
bool isPerfect(int n);
using namespace std;
int main() {
long long perfect = 0;
int first = 0;
first = (pow(2, 2 - 1))*(pow(2, 2) - 1);
cout << first << endl;
for (int i = 3, j = 1; j < 5; i += 2) {
if (isPerfect(i)) {
perfect = (pow(2, i - 1)*(pow(2, i) - 1));
cout << perfect << endl;
j++;
}
}
// pause and exit
getchar();
getchar();
return 0;
}
bool isPerfect(int n)
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else if (n % 2 == 0) {
return false;
}
else {
bool prime = true;
for (int i = 3; i < n; i += 2) {
if (n%i == 0) {
prime = false;
break;
}
}
return prime;
}
}
You're pretty much complicating this task.
Here's what I came up with:
#include <iostream>
using namespace std;
bool isPerfect(long long n);
int main()
{
int count = 5;
long long sum = 1;
for (int i = 3; count >= 0; i += 2)
{
sum += i * i * i;
if (isPerfect(sum))
{
cout << sum << endl;
count--;
}
}
system("pause");
return 0;
}
bool isPerfect(long long n)
{
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
sum += i;
}
return sum == n;
}
It sure isn't perfect, but will do for 5 numbers. Consider that it'll be very slow for more than 5 numbers.

Project Euler 10 exercise

What is the sum of all the primes below 2000000?
Example of sum below 10 is 2+3+5+7 = 17
I wrote this code, but still getting the wrong answers:
I tested for numbers lower than a few hundreds, and it has shown the correct answers.
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(long n)
{
if (n < 2)
return false;
if (n == 2)
return true;
if (n == 3)
return true;
int k = 3;
int z = (int)(sqrt(n) + 1); // square root the n, because one of the product must be lower than 6, if squared root of 36
if (n % 2 == 0)
return false;
while (n % k != 0)
{
k += 2;
if (k >= z)
return true;
}
return false;
}
long primeSumBelow(long x)
{
long long total = 0;
for (int i = 0; i < x; i++) // looping for times of prime appearing
{
if (isPrime(i) == true)
total += i;
if (isPrime(i) == false)
total += 0;
}
cout << "fd" << endl;
return total;
}
int main()
{
cout << primeSumBelow(20) << endl;
cout << primeSumBelow(2000000) << endl;
system("pause");
return 0;
}
The total counter's type is correctly long long. Unfortunately the function primeSumBelow returns only long so, depending on the platform, the correctly calculated result is truncated when it's returned from this function.

Recursive Fibonacci

I'm having a hard time understanding why
#include <iostream>
using namespace std;
int fib(int x) {
if (x == 1) {
return 1;
} else {
return fib(x-1)+fib(x-2);
}
}
int main() {
cout << fib(5) << endl;
}
results in a segmentation fault. Once x gets down to 1 shouldn't it eventually return?
When x==2 you call fib(1) and fib(0):
return fib(2-1)+fib(2-2);
Consider what will happen when fib(0) is evaluated...
The reason is because Fibonacci sequence starts with two known entities, 0 and 1. Your code only checks for one of them (being one).
Change your code to
int fib(int x) {
if (x == 0)
return 0;
if (x == 1)
return 1;
return fib(x-1)+fib(x-2);
}
To include both 0 and 1.
Why not use iterative algorithm?
int fib(int n)
{
int a = 1, b = 1;
for (int i = 3; i <= n; i++) {
int c = a + b;
a = b;
b = c;
}
return b;
}
By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.
#include <iostream>
using namespace std;
int Fibonacci(int);
int main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else
cout << number << " Fibonacci is: " << Fibonacci(number) << endl;
}
int Fibonacci(int x)
{
if (x < 2){
return x;
}
return (Fibonacci (x - 1) + Fibonacci (x - 2));
}
I think this solution is short and seem looks nice:
long long fib(int n){
return n<=2?1:fib(n-1)+fib(n-2);
}
Edit : as jweyrich mentioned, true recursive function should be:
long long fib(int n){
return n<2?n:fib(n-1)+fib(n-2);
}
(because fib(0) = 0. but base on above recursive formula, fib(0) will be 1)
To understand recursion algorithm, you should draw to your paper, and the most important thing is : "Think normal as often".
This is my solution to fibonacci problem with recursion.
#include <iostream>
using namespace std;
int fibonacci(int n){
if(n<=0)
return 0;
else if(n==1 || n==2)
return 1;
else
return (fibonacci(n-1)+fibonacci(n-2));
}
int main() {
cout << fibonacci(8);
return 0;
}
int fib(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
in fibonacci sequence first 2 numbers always sequels to 1 then every time the value became 1 or 2 it must return 1
int fib(int x)
{
if (x == 0)
return 0;
else if (x == 1 || x == 2)
return 1;
else
return (fib(x - 1) + fib(x - 2));
}
int fib(int x)
{
if (x < 2)
return x;
else
return (fib(x - 1) + fib(x - 2));
}
if(n==1 || n==0){
return n;
}else{
return fib(n-1) + fib(n-2);
}
However, using recursion to get fibonacci number is bad practice, because function is called about 8.5 times than received number.
E.g. to get fibonacci number of 30 (1346269) - function is called 7049122 times!
My solution is:
#include <iostream>
int fib(int number);
void call_fib(void);
int main()
{
call_fib();
return 0;
}
void call_fib(void)
{
int input;
std::cout<<"enter a number\t";
std::cin>> input;
if (input <0)
{
input=0;
std::cout<<"that is not a valid input\n" ;
call_fib();
}
else
{
std::cout<<"the "<<input <<"th fibonacci number is "<<fib(input);
}
}
int fib(int x)
{
if (x==0){return 0;}
else if (x==2 || x==1)
{
return 1;
}
else if (x>0)
{
return fib(x-1)+fib(x-2);
}
else
return -1;
}
it returns fib(0)=0 and error if negitive
I think it's the best solution of fibonacci using recursion.
#include<bits/stdc++.h>
typedef unsigned long long ull;
typedef long long ll;
ull FIBO[100005];
using namespace std;
ull fibo(ull n)
{
if(n==1||n==0)
return n;
if(FIBO[n]!=0)
return FIBO[n];
FIBO[n] = (fibo(n-1)+fibo(n-2));
return FIBO[n];
}
int main()
{
for(long long i =34;i<=60;i++)
cout<<fibo(i)<<" " ;
return 0;
}
I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.
unsigned fib(unsigned n) {
if(n == 0) return 0;
if(n == 1) return 1;
return fib(n-1) + fib(n-2);
}
This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).
You should better use this approach or if you want to use recursion try this:
unsigned fib(unsigned n, unsigned prev1 = 0, unsigned prev2 = 1, int depth = 2)
{
if(n == 0) return 0;
if(n == 1) return 1;
if(depth < n) return fib(n, prev2, prev1+prev2, depth+1);
return prev1+prev2;
}
This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.