I need to write a program in C++ to find the closest Fibonacci number to the input number. I patched together a program that tells the Fibonacci number in the nth place, I've included it's code. Next is this task of finding the closest number to the input. What I've gathered is that I probably need to use a binary search/decision tree to rule out the bad numbers. I can generate the Fibonacci numbers so I'm that close. I need a point in the right direction to get me going. I'm pretty sure Binet's formula is involved as well as the golden ratio.
Here's the code for my original program:
int fib(int n)
{
if (n <= 1)
return (n);
return fib(n - 1) + fib(n - 2);
}
int main()
{
cout << "Enter a number greater than -1 and see what the n'th place in the fibbonaci sequence equals.\n";
cin >> n;
fib(n);
if (n >= 0)
cout << "n'th Fibonacci number is " << fib(n) << "\n";
else
cout << "\nInvalid number.\n\n";
return 0;
}
So I found some code that calculated the index for me. I made minor adjustments for input.
#include <iostream>
using namespace std;
int findIndex(int n)
{
if (n <= 1)
return n;
int a = 0, b = 1, c = 1;
int res = 1;
while (c < n)
{
c = a + b;
res++;
a = b;
b = c;
}
return res;
}
int main()
{
int fib_number;
cout << "Please enter a single integer number to see the closest index in the Fibonacci sequence.\n";
cin >> fib_number;
int result = findIndex(fib_number);
cout << "The Fibonacci index is " << result << ".";
}
Related
Can someone help me in this?
This is a c++ program that I need to find prime numbers of fibonacci series.
the question says that after you enter the n ( the number of fibonacci series ) the program has to extract the prime numbers from it, and then, if the sum of those prime numbers is an odd number, it has to show 'A' and if it's even, it should show 'D'. The problem is I know how to find both fibonacci series and prime numbers, but I can't merge them.
And I need to keep the code as simple as possible
Can someone help me in this?
This one is for fibonacci series:
#include <iostream>
#include <conio.h>
using namespace std;
int main(){
int n, a = 1, b = 1, c;
cin >> n;
cout << a << endl;
cout << b << endl;
int i = 2;
while (i < n)
{
c = a + b;
cout << c << endl;
a = b;
b = c;
i++;
}
getch();
}
And this one is for prime numbers :
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int a, b = 1, r = 1, c = 0, x, m;
cout << "please enter number :";
cin >> a;
while (b <= a) {
m = a;
x = b;
while (x != 0) {
r = m % x;
m = x;
x = r;
}
if (m == 1){
c++;
b++;
}
cout << c;
getch();
}
I have to put them together so i can extract the prime numbers in the fibonacci, but I dont know how.
And, I need it to show the prime numbers but my code shows how many numbers are prime
One solution could be to make a function to find the n'th fibonacci number, another function to test if a number is prime, and then loop over the fibonacci number to find the primes
#include <iostream>
int fib(int n) { /* code */ }
bool is_prime(int n) { /* code */ }
int sum_of_prime_in_fib(int lim)
{
int sum = 0;
// loop over the fibonacci number to sum the primes
for (int i = 1; i <= lim; ++i) {
int f = fib(i);
if (is_prime(f))
sum += f;
}
return sum;
}
int main()
{
int n;
std::cout << "please enter number :";
std::cin >> n; //remember to check for errors, which I wont do
std::cout << "the sum of primes is: " << sum_of_prime_in_fib(n) << "\n";
}
I have left the implementation of the two functions as an exercise
Since you did not include conio.h content, I will pose a solution from bare-bone.
This question revolves around several stages.
get all fibonacci sequence in a list
use fibonacci sequence to find if any prime numbers exist (put them in a list)
calculate the sum of the prime numbers from that list
if the sum is even, print "A" otherwise print "D".
The code can be broken down to several functions to make it easier and more intuitive.
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
vector<int> generate_fibonacci(int n){
int a = 1, b = 1, c;
//cout << a << endl;
//cout << b << endl;
int i = 2;
vector<int> f;
f.push_back(a);
f.push_back(b);//assuming that the a,b are part of the fibonacci
while (i < n)
{
c = a + b;
f.push_back(c);
a = b;
b = c;
i++;
}
return f;
}
bool is_prime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
vector<int> find_prime_from_f(vector<int> v){
vector<int> fp;
for(int i: v){
if(is_prime(i))
{
fp.push_back(i);
}
}
return fp;
}
int main(){
cout << "please enter the number of fibonacci" << endl;
int n;
cin >> n;
vector<int> fibonacciNumber = generate_fibonacci(n);
vector<int> fibonacciPrime = find_prime_from_f(fibonacciNumber);
int sum;
for(int i: fibonacciPrime)
{
sum += i;
}
if(sum %2 != 0) cout << "A" <<endl; //if it is odd
else cout << "D" <<endl; //if it is even
}
You can of course tailor some of the details of these functions, including adding some bound checking for negative numbers, and optimize the algorithm by using array, doing the calculation and checking on the fly, or simplify the code a little. However, this should serve as a starting point for your further implementation.
am running these two functions that do the same calculation "summing the first N integers " then compare the run times for each one. The program works fine with small inputs, but the problem is when I input large numbers like 1000000, it calculates the first method "the iterativeSum()" then as soon as it gets to the the recursiveSum() it stops working.
am not sure but do you think that this might be because of the cout?
#include <stdio.h>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void iterativeSum(int);
int RecursiveSum(int);
int main()
{
long long posInt;
std::cout << "Enter a positive integer: ";
std::cin >> posInt;
int start_s=clock();
iterativeSum(posInt);
int stop_s=clock();
int start_s1=clock();
cout << "\nThe recursive algorithm to sum the first N integers of "<< posInt << " is: "<< RecursiveSum(posInt) << endl;
int stop_s1=clock();
cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)/1000 << endl;
cout << "time: " << (stop_s1-start_s1)/double(CLOCKS_PER_SEC)/1000 << endl;
return 0;
}
void iterativeSum(int posInt)
{
//positive Integer >=0
int sum = 0;
//loop through and get only postive integers and sum them up.
// postcondion met at i = 0
for(int i = 0; i <= posInt;i++)
{
sum +=i;
}
//output the positive integers to the screen
std::cout <<"\nThe iterative algorithm to sum the first N integers of " <<posInt <<" is: " << sum << "\n";
}
int RecursiveSum(int n)
{
if(n == 1) // base case
{
return 1;
}
else
{
return n + RecursiveSum(n - 1); //This is n + (n - 1) + (n - 2) ....
}
}
You may need an arbitrary precision arithmetic library like GMPlib, to avoid arithmetic overflows. And you should be afraid of stack overflow.
The call stack is often limited (to e.g. a megabyte). See this
I want to ask the user for an integer, and print the prime factors.
Example: User enters 100, program displays 2 2 5 5
So far I have the following:
#include <iostream>
using namespace std;
void factors(int n){
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
cout << z;
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{cout << n << "\n";}
}
int main()
{
int x;
cout << "Input positive integer greater than 1: ";
cin >> x;
factors(x);
cout << "The result: " << x;
return 0;}
My question is how do I get my main function to communicate with the factors procedure. I run the program, I get the message asking for input, I input 12, I get the message "The result" but with a number of 25, and also 12, the number that the user input. it's like the program is avoiding my factors(int n) procedure. Help with the syntax please?!?
My issue is with the syntax I think.
Because I found the following function to help with listing prime factors:
Finding prime factors
-user44810
define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
Thank you!!!
Try this
#include <iostream>
#include <vector>
using namespace std;
vector<int> factors(int n){
vector<int> result;
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
result.push_back(z);
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
result.push_back(z);
return result;
}
int main()
{
int x;
cout << "Input positive integer greater than 1: ";
cin >> x;
vector<int> result_factors = factors(x);
cout << "The result: ";
for (int i: result_factors)
cout << "i ";
cout << endl;
return 0;
}
I changed your factor() function to output nothing on cout but saving the factors in a vector and returning it. In the main function, iterate over the result vector and print the values to cout.
So the biggest issue is that there is a missing brace at the end of your factors function. you need to add another brace after the if (n > 1) brace. Also, there is a missing semicolon at the end of the last cout that will throw an error.
Another issue that won't prevent the code from running is that when you print "The result: " << x you will be giving the same value as the user input.
If you want your main function to print out the result from factors() at that spot, then the function needs to return the data instead of printing it. To fix this, the factors function can be made to return a string with the output you want:
//return a string with the output
string factors(int n){
//create a string to save the output to
string factorlist = "";
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
//append z to the end of the string and add a space to make it easier to read
factorlist+=to_string(z)+" ";
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{
//append n to the end of the string and add a newline
factorlist+=to_string(n)+"\n";
}
//output the string factorlist to wherever the function was called from
return factorlist;
}
then on the lines that look like:
factors(x);
cout << "The result: " << x
Should be:
cout << "The result: " << factors(x);
Currently, you are just printing out the value of x that the user input. If you want to save the value of factors(x) you would need to set a variable equal to it like this:
string FactorsResult = factors(x)
And then print it; or, as in the corrected code above, just print it directly in the cout statement.
I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)
I need a program in C++ or C that will calculate prime factor, for Example you input 135 I want an output to be like this (3^3)(5^1) instead of 3,3,3,5.
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
void get_divisors(int n);
int main()
{
int n = 0;
cout << "Enter a number:";
cin >> n;
get_divisors(n);
cout << endl;
}
void get_divisors(int n)
{
int i;
double sqrt_of_n = sqrt(n);
for (i = 2; i <= sqrt_of_n; i++)
if (n % i == 0)
{
cout << i << ", ";
get_divisors(n / i);
return;
}
cout << n;
}
Use std::map<int, int> to contain the prime number (first integer) and the number of occurances of that prime number (second integer).
So when you have a prime, find the value in the map and if it is not in the map, insert it.
If the prime already exists, increment the count.
When printing, you iterate through the map, printing the prime number, then the '^' character, then the count of primes.
Details left as an exercise for the reader.