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.
Related
I want to write a program that takes 5 inputs and adds even numbers and multiplies odd numbers, but I do not know how to do this after I know which number is odd and which is even.
#include<iostream>
using namespace std;
int main(){
int a, b, c, d, e, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum8, sum9, sum10;
cout<<"Please Enter 5 Integers\t:\t";
cin>>a>>b>>c>>d>>e;
if(a%2==0 && b%2==0)
{
cout<<a+b;
sum1 = a+b;
}
if(a%2==0 && c%2==0)
{
cout<<a+c;
sum2 = a+c;
}
if(a%2==0 && d%2==0)
{
cout<<a+d;
sum3 = a+d;
}
if(a%2==0 && e%2==0)
{
cout<<a+e;
sum4 = a+e;
}
if(b%2==0 && c%2==0)
{
cout<<b+c;
sum5 = b+c;
}
if(b%2==0 && d%2==0)
{
cout<< b+d;
sum6 = b+d;
}
if(b%2==0 && e%2==0)
{
cout<<b+e;
sum7 = b+e;
}
if(c%2==0 && d%2==0)
{
cout<< c+d;
sum8 = c+d;
}
if(c%2==0 && e%2==0)
{
cout<<c+e;
sum9 = c+e;
}
if(d%2==0 && e%2==0)
{
cout<<d+e;
sum10 = d+e;
}
return 0;
}
You don't need all of those variables, and you certainly do not need to check every combination of variables one at a time. A simple loop will suffice.
Try something more like this:
#include <iostream>
using namespace std;
int main(){
int number, sum = 0, product = 1;
cout << "Please Enter 5 Integers\t:\t";
for(int i = 0; i < 5; ++i)
{
cin >> number;
if (number % 2 == 0)
sum += number;
else
product *= number;
}
cout << sum << ' ' << product << endl;
return 0;
}
This is a very rough and relatively simple solution. It throws an exception if the input is not convertible to an int. And since the exception is not caught anywhere, the program exits if the user enters invalid input.
std::vector is roughly the same as an array. It spares you from having to declare 5 variables, and instead stores all the input values in the vector.
The stoi() function converts a string to an integer (stoi = string to integer).
#include <iostream>
#include <vector>
#include <string>
int main() {
bool outputSum, outputProduct = false;
std::vector<int> input;
for (int i = 0; i < 5; i++) {
std::string entered_string;
int entered_value = 0;
std::cout << "Please enter a number: ";
std::cin>>entered_string;
entered_value = stoi(entered_string);
input.emplace_back(entered_value);
}
int sum = 0;
int product = 1;
for (int i = 0; i < 5; i++) {
if (input[i] % 2 == 0) {
sum += input[i];
outputSum = true;
} else {
product *= input[i];
outputProduct = true;
}
}
if (outputSum) {
std::cout << "Sum: " << sum << std::endl;
}
if (outputProduct) {
std::cout << "Product: " << product << std::endl;
}
return 0;
}
I am assuming that you do not want to add the sum and the product at the end, since you didn't specify what exactly you want your output to be.
Understanding of loops makes this code very simple. You store the five numbers, but they're disconnected from each other since they're stored in separate variables. Now you have to write the many tests that you have, and it's a big mess and you feel like there has to be an easier way.
As other answers show, if you don't need to use the numbers later, then you don't need five variables for input; one is sufficient. You store the input into a variable, check if it's even/odd, and update the sum or product variable accordingly. The repetition of a loop makes this work.
If you need to display the numbers or otherwise keep them around for other purposes, an array (or std::vector in this case) comes in handy.
The code below demonstrates a C++ Standard Library function (std::reduce()) that can generate the sum or the product. Other answers do a fine job showing how to calculate those values manually. And just to re-iterate, this solution would be considered viable only if you needed the numbers for some other task.
#include <functional> // std::multiplies
#include <iostream>
#include <numeric> // std::reduce
#include <vector>
void print_container(std::vector<int> v) {
for (auto i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
constexpr int numInputs = 5;
std::vector<int> evenNums;
std::vector<int> oddNums;
for (int tmp, i = 0; i < numInputs && std::cin >> tmp; ++i) {
tmp & 1 ? oddNums.push_back(tmp) : evenNums.push_back(tmp);
}
int sum = std::reduce(evenNums.begin(), evenNums.end(), 0);
int product = std::reduce(oddNums.begin(), oddNums.end(), 1,
std::multiplies<int>());
std::cout << "Even numbers: ";
print_container(evenNums);
std::cout << "Odd numbers: ";
print_container(oddNums);
std::cout << "Sum of evens: " << sum << "\nProduct of odds: " << product << '\n';
}
Output (with input being 1 2 3 4 5):
Even numbers: 2 4
Odd numbers: 1 3 5
Sum of evens: 6
Product of odds: 15
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 << ".";
}
thanks to your help last night I was able to get my program computing my input properly, but now I am have trouble formatting my output properly. This is the problem:
My program should only print "is prime" on lines with prime numbers. But it prints on ever line like this:
http://oi42.tinypic.com/30igbvq.jpg
I cannot for the life of me figure out why it is doing this, all of my functions should work.
Stack I need your help again!
#include <iostream>
using namespace std;
void primecheck(int x); // proto
void countr(int rnm, int lnm); // proto
void prime(int x) // this function finds the prime factors of a number.
{
int lastr = 2;
int count = 0;
while (lastr < x)
{
if (x % lastr == 0)
{
cout << x << " " << lastr << "*";
x /= lastr;
}
else
++lastr;
}
primecheck(x); // calls to check if number is prime, "Is prime"
}
void console(int rnum, int lnum) // this prompts the user for two numbers then stores the answers
{
cout << "please enter two numbers ";
cin >> rnum;
cin >> lnum;
countr(rnum, lnum);
}
void countr(int rnm, int lnm) // this function loops the prime function until all the numbers are computed
{
int i = rnm;
do{
prime(i);
i++;
} while (i <= lnm);
return;
}
int main() // main, calls console then pauses when finished
{
int e = 0;
int r = 0;
console(e, r);
system("PAUSE");
}
void primecheck(int x) // checks to see if then number is prime. if counter is equal to 2 than number is prime.
{
int counting = 0;
for (int a = 1; a <= x; a++)
{
if (x %a == 0)
{
counting++;
}
}
if (counting == 2)
{
cout << x << " is prime " << endl;
}
else
{
cout << x << endl;
}
}
You're using a /= operator in prime(). That's an assignment operator and is modifying the value of x, making x always prime whenever primecheck() is called.
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.
Basically I would like to make a small little program that when u enter a number (say 145) it read the 3 digits and prints the largest one.
int a, b, c, max;
cout << "Enter a, b and c: ";
cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
cout << "Max is " << max << "\n";
I was think of using something like this, but I have no idea how to get the computer to read each individual digit.
thanks!
Change int on the first line to char.
#include <iostream>
int main() {
char a, b, c, max;
std::cout << "Enter a, b and c: ";
std::cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
std::cout << "Max is " << max << "\n";
}
This works, but is really not the right way to approach this problem IMO for C++.
This is slightly better, but with no kind of input validation:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string s;
std::cout << "Enter a number: ";
std::cin >> s;
char maxChar = *max_element(s.begin(), s.end());
std::cout << "Max is " << maxChar << "\n";
}
No need to resort to anything C++-specific when plain C will do it in less time than the conversions in keith.layne's answer if you already have the number in hand:
unsigned big_digit(unsigned value)
{
unsigned biggest = 0;
while (value) {
unsigned digit = value % 10;
if ( digit > biggest )
biggest = digit;
value /= 10;
}
return biggest;
}
Hope that wasn't homework.
You can make use of %(modulus) for such operations.
I think this LINK will do you justice
Basically I would like to make a small little program that when u enter a number (say 145) it read the 3 digits and prints the largest one.
int a, b, c, max;
cout << "Enter a, b and c: ";
cin >> a >> b >> c;
max = a;
if (b>max)
max = b;
if (c>max)
max = c;
cout << "Max is " << max << "\n";
I was think of using something like this, but I have no idea how to get the computer to read each individual digit. thanks!
While the answer using by keith.layne with strings works if you would like an answer that doesn't use strings you can just use integer division and modulus to get the same result:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int userInput, max;
cout << "Input a number and I'll give the biggest digit: ";
cin >> userInput;
cout << "The max digit of " << userInput << " is ";
max = userInput % 10; // sets one's digit to max
userInput /= 10; // reduces number by a digit
while(userInput > 0) // while number has remaining digits
{
if(userInput % 10 > max)// checks for a new max
{
max = userInput % 10;
}
userInput /= 10; // reduces number by a digit
}
cout << max << endl;
return 0;
}
spec :must be a4 digit number, either - or +, Modify this code to get your desired output. cheers!
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
int a, b, c, d, rem;
int no;
int max = 0;
int min = 0;
cin >> no;
if (no < 0)
no = abs(no);
a = no/1000;
rem = no%1000;
b = rem/100;
rem = rem%100;
c = rem/10;
rem = rem%10;
//cout<<a;
if(a > 0 && a <= 9)
{
if(a > max)
max = a;
else min = a;
if(b > max)
max = b;
else min = b;
if(c > max)
max = c;
else min = c;
if(rem > max)
max = rem;
else min = rem;
if(max > min)
cout << max << endl;
else
cout << min << endl;
}
else
cout<<"Invalid no"<<endl;
return 0;
}
I came up with this while trying to solve a codewars problem.
int i = 0;
int num_ = num; //we will need a dummy, num is the original
while(num_ != 0){ //count the number of digits
num_ /= 10;
i++; //yayyy
}
int *ptr = new int[i]; //dynamic array to store individual numbers
int pos = 0;
while(1){ //copy digits to dynamic array
if(num > 10){
num_ = num%10;
ptr[pos] = num_;
num /= 10;
pos++;
}
else{
num_ = num%10;
ptr[pos] = num_;
break;
} //array now contains our digits
}