print the number of operations and time taken to compute Fibonacci numbers - c++

How would I print the number of operations and time taken to compute Fibonacci numbers recursively versus that needed to compute them iteratively. Here is my code currently:
#include<bits/stdc++.h>
using namespace std;
int iterative(int n){
int num1 = 0, num2 = 1, num3, j;
cout<<num1<<" "<<num2<< " ";
if( n == 0)
return num1;
for (j = 2; j <= n; j++){
num3 = num1 + num2;
cout<<num3<<" ";
num1 = num2;
num2 = num3;
}
return num2;
}
int recursive(int num){
if (num <= 1)
return num;
return recursive(num-1) + recursive(num-2);
}
int main (){
// main method to test the function
int n;
cout << "Enter a value for n: ";
cin >> n;
printf("\nWhen n is %d ,the iterative method number is : %d", n,iterative(n));
getchar();
printf("\nWhen n is %d ,the recursive method number is : %d", n,recursive(n));
getchar();
return 0;
}

Try something like this. As mentioned above you should not using include #include<bits/stdc++.h> . If you want to know more about problems with that include you should read this.
#include <chrono>
#include <iostream>
int iterative(int n, int &cnt){
int num1 = 0, num2 = 1, num3, j;
std::cout<<num1<<" "<<num2<< " ";
if( n == 0)
return num1;
for (j = 2; j <= n; j++){
num3 = num1 + num2;
std::cout<<num3<<" ";
num1 = num2;
num2 = num3;
cnt++;
}
return num2;
}
int recursive(int num, int &cnt){
if (num <= 1)
return num;
cnt++;
return recursive(num-1, cnt) + recursive(num-2, cnt);
}
int main (){
// main method to test the function
int n;
int cnt = 0;
std::cout << "Enter a value for n: ";
std::cin >> n;
auto start = std::chrono::high_resolution_clock::now();
int iterativeNum = iterative(n, cnt);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = end - start;
printf("\nWhen n is %d , num of operation is : %d , time spent is : %f , the iterative method number is : %d", n, cnt, duration.count() ,iterativeNum);
getchar();
cnt = 0;
start = std::chrono::high_resolution_clock::now();
int recNum = recursive(n, cnt);
end = std::chrono::high_resolution_clock::now();
duration = end - start;
cnt = 0;
printf("\nWhen n is %d , num of operation is : %d , time spent is : %f , the recursive method number is : %d" , n, cnt, duration.count(), recNum);
getchar();
return 0;
}

Related

I was doing a code for , "Count Digits " , Evenly divides means whether N is divisible by a digit i.e. leaves a remainder 0 when divided

#include<bits/stdc++.h>
using namespace std;
int main() {
int n,m,z;
cout<<"enter n: ";
cin>>n;
z=n;
int count=0;
while(n>0){
m = n % 10;
if(z%m == 0){
count++;
}
n=n/10;
}
cout<<count;
}
Code should work like that ex - for n = 12, it is divisible by both 1 , 2 so, the output will be 2
if i am taking any value which have '0' in their last then it is not working ..and i am getting an error "Floating-point exception (SIGFPE)".
Could anyone help me to get rid out of this.
This while loop
while(n>0){
m = n % 10;
if(z%m == 0){
count++;
}
n=n/10;
}
does not make a great sense. For example m can be equal to 0 after this statement
m = n % 10;
and as a result this statement
if(z%m == 0){
produces a run-time error.
The program can look for example the following way
#include <iostream>
int main()
{
unsigned int count = 0;
int n;
std::cout << "enter n: ";
if ( std::cin >> n )
{
const int Base = 10;
int tmp = n;
do
{
int digit = tmp % Base;
if ( digit != 0 && n % digit == 0 ) ++count;
} while ( tmp /= Base );
}
std::cout << "count = " << count << '\n';
}

I'm having problems with Project Euler #8

Here is my code for Project Euler #8. It reads the 1000-digit number from a file by reading each character, and then converting that to an integer before storing it into an array. I then intended on using loops to read groupings of 13 digits, 0-12, 1-13, 2-14, etc. And multiplying them. If the result is larger than the previous largest one, it is stored into num2.
#include <iostream>
#include <fstream>
using namespace std;
int num1=1, num2;
int main(){
int digitArray[1000];
char ctemp;
int itemp;
ifstream myfile;
myfile.open("1000 digit number.txt");
if(myfile.is_open()){
for(int i=0; i < 1000; i++){
myfile >> ctemp;
itemp = ctemp - '0';
digitArray[i] = itemp;
}
}
myfile.close();
for(int i = 0; i < 1000; i++){
int j = i;
while(j != (i+13)){
num1 *= digitArray[j];
j++;
if(j == 1000){
break;
}
}
if(num1 > num2){
num2 = num1;
} else {}
}
cout << num2 << endl;
return 0;
}
This code outputs the value 5000940, which is not the correct answer. Help?
num1 is not initialized to 1 for every 13 contiguous numbers. Also check the break condition before any out of bound index is accessed.
for(int i = 0; i < 1000; i++){
int j = i;
num1=1;
while(j != (i+13)){
if(j == 1000){
break;
}
num1 *= digitArray[j];
j++;
}
if(num1 > num2){
num2 = num1;
}
}
Streamlining the algorithm I came up with this:
#include <iostream>
#include <string>
#include <cstdint>
int main(){
std::string input;
// std::cin >> input;
input = "1101111111111133111111111111122";
uint64_t prod = 1;
uint64_t m = 0;
size_t count = 0;
for (auto p = input.begin(); p != input.end(); ++p) {
prod *= *p - '0';
if (prod == 0) {
prod = 1;
count = 0;
} else {
if (count++ >= 13) {
prod /= *(p - 13) - '0';
}
if ((count >= 13) && (prod > m)) m = prod;
}
}
std::cout << "max = " << m << std::endl;
}
The approach uses a sliding window updating the product from digit to digit. It starts with a window size of 0 and grows it to 13 before doing that and every time a '0' is seen the window size is reset to grow again.
Here is what worked:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int digitArray[1000];
char ctemp;
int itemp;
ifstream myfile;
myfile.open("1000 digit number.txt");
if(myfile.is_open()){
for(int i=0; i < 1000; i++){
myfile >> ctemp;
itemp = ctemp - '0';
digitArray[i] = itemp;
}
}
myfile.close();
long num2;
for(int i = 0; i < 1000; i++){
int j = i;
long num1 = 1;
while(j != (i+13)){
if(j == 1000){
break;
}
num1 *= digitArray[j];
j++;
}
cout << endl;
if(num1 > num2){
num2 = num1;
} else {}
}
cout << num2 << endl;
return 0;
}
Needed to make num2 a long, moved the break up, and initialized num1 inside of the for loop instead of outside. Honestly didn't expect to need a value that large. Embarrassing but whatever. Thanks for the help.

Adding fractions in C++ without using functions

I'm New to C++ and I want to know if there's a way to add two fractions by using the LCM, as i want to display the added fractions in reduced form. I also can't use functions or string or thing of that nature. I attempted to answer it using GCD but this isn't the assignment question so i could some help.
Such as 3/8 + 5/12 = 19/24, i know this it the answer, i just don't know how to get c++ to display it
int main()
int num1,denom1,num2,denom2,num3,denom3,GCD,i;
while(denom1!=0 || denom2!=0)
{
cout<<"Enter Numerator of fraction one ";
cin>>num1;
cout<<"Enter Denominator of fraction one ";
cin>>denom1;
cout<<"Enter Numerator of fraction two ";
cin>>num2;
cout<<"Enter Denominator of fraction two ";
cin>>denom2;
num3 = (num1 * denom2) + (denom1 * num2);
denom3 = denom1 * denom2;
cout<<"The answer is "<<num3<<"/"<<denom3;
}
if (denom3 == 0)
{
exit;
}
for (i = 1; i <= num3 && i <= denom3; ++i)
{
if (num3 % i == 0 && denom3 % i == 0)
GCD = i;
}
cout <<"\n The added fraction is " << num3/GCD << "/" << denom3/GCD;
cout << endl;
return 0;
}
You probably want to implement something like
class Fraction{
private:
int numerator;
int denominator;
public:
Fraction (int n, int dn);
void reduce ();
Fraction add (Fraction a, Fraction b);
Fraction subtract (Fraction a, Fraction b);
}
I got this code. I bet it can be simplified, but I think you will understand it.
#include <iostream>
using namespace std;
int main()
{
int tempNum , tempDenom;
int denom1=8 , denom2=12 , denom3, num1=3 , num2=5, num3;
for(int i = 1 ; ;i++){ // this loop will work untill you find
multiplier for the first fraction
if ( (denom1 * i) % denom2 == 0){
denom3 = denom1 * i;
num1 = num1 * i;
break; // when you find it, you will end the
} //loop with break
}
for(int i = 1 ; ;i++){ // this loop will work untill you find
multiplier for the second fraction
if ( (denom2 * i) % denom1 == 0){
num2 = num2 * i;
num3 = num1 + num2;
break; // when you find it, you will end the
} loop with break
}
for (int i = num3 ; i > 1 ; i--){
tempNum = num3 % i; //the % gives you the rest of the divison
tempDenom = denom3 % i;
if(tempNum == 0 && tempDenom == 0){
num3 = num3 / i;
denom3 = denom3 / i;
break; // you have simplified the fraction
}
}
cout << "The result is : " << num3 << "/" << denom3;
}

Q - Given positive integers- m,n.. Find and print the values of 3^min(m,n) and 2^max(m,n)

Using C++ have written foloowing :
#include <iostream>
using namespace std;
int main()
{
int m,n;
int threemin, twomax;
threemin = 1; twomax = 1;
cout<<"Enter m"<<"Enter n";
cin>>m>>n;
int i,j;
for ((i = 1, j = 1) ; ( (i <= m), (j <= n) ) ; (i++,j++))
{
if (m>n){ i <= n ; threemin = threemin*3;} // for changing max value of i if m > n because we want to print 3^min(m,n)
else { threemin = threemin*3 ;} ; //
if (m>n){ j <= m ; twomax = twomax*2;} // same for changing j
else { twomax = twomax*2 ; }
}
cout<<"Threemax is"<<threemin<<"Twomax is"<<twomax;
return 0;
}
Issue -
For example m = 4 and n = 3 but here max(4,3) = 4 and min(4,3) = So, I have tried to such code which will give 3^min(m,n) and 2 ^max(4,3).
But Output comes out to be threemin = 3^3 = 81 and twomax = 2^3 = 8. Both are taking n as their exponent.
I am beginner .Kindly help me rectifying .
You can instead do something like this:
#include <iostream>
using namespace std;
int main()
{
int m, n, lesser, greater, threemin=1, twomax=1, i=1;
cout << "Enter m " << "Enter n";
cin >> m >> n;
lesser = min(m, n); // find smallest
greater = max(m, n); // find largest
while(i <= lesser) { // ride on smallest untill done
threemin *= 3;
twomax *= 2;
i++;
}
while(i <= greater) { // continue for largest
twomax *= 2;
i++;
}
cout << "Threemin is: " << threemin << ", Twomax is: " << twomax;
return 0;
}

C++ Programming help

You create a program that displays the sum of even integers between and including two numbers entered by the user ..
ex) 2 and 7 = the sum of 12 (2+4+6)
this is what i have so far! butt if u can just put me in the right direction that would be helpful
//Advanced30.cpp - displays the sum of the even integers between and
//including two numbers entered by the user
//Created/revised by <your name> on <current date>
#include <iostream>
using namespace std;
int main()
{
// declare variables
int num1 = 0;
int num2 = 0;
int sum= 0;
cout << "Enter the First Number:" << endl;
cin >> num1;
cout << "Enter the Second Number:" << endl;
cin >> num2;
if ( num1 > num2)
{
cout << "Invalid entry. Final number must be less than the first number. Please try again." << endl;
}
for ( int sum = (((num1 + 1)/2)*2); num1 <= (((num2 + 1)/2)*2) ; sum = 2 + (((num1 + 1)/2)*2) )
return 0;
} //end of main function
In your for loop it should be like this.
double sum = 0.0;
for(i = num1; i <= num2; i++){
if(i % 2 == 0){ // Is our number even
sum += i;
}
}
That's it and it print out sum.
I would simplify your for loop
for(int i = num1; i <= num2; i++) {
if(i % 2 == 0) sum += i;
}
This will look at twice as many numbers, but honestly that's not all that much more expensive.
You could also do it in O(1) time by taking advantage of the fact that the sum 1..n == n*(n+1)
Here's a very simple example in Java, translating it to C++ won't be too difficult I hope :) no C++ compiler on this machine :-X
import java.util.*;
class DoubleSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int low = (num1 - 1)/ 2;
int high = num2 / 2;
int sumLow = (low*(low + 1));
int sumHigh = (high*(high + 1));
int sum = sumHigh - sumLow;
System.out.println(sum);
}
}
You are using the same variable to control the for loop and to the sum, this won't work. Try this:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
for (int i = even1; i <= even2; i += 2) sum += i;
Note that you don't really need a for loop:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
// how many numbers you will sum (remember they are even, so we need to divide by 2)
int count = 1 + (even2 - even1)/2;
sum = (even1 + even2) * (count/2);
if (count % 2 == 1) sum += (even1 + even2)/2;
for(int i = num1; i <= num2; i++)
{
if(!(i & 1))
sum += i;
}
Your code would end up in an infinite loop.
Look at the for() loop. You have the condition
num1 <= (((num2 + 1)/2)*2)
to determine whether your loop terminates. However, since num1 itself is never incremented, and num1 < num2 is guaranteed, this condition will always be true - which means your for loop would never end. I would also suggest using a separate looping variable.