Saturday, 21 June 2014

C Program to Determine the Sum of Harmonic Series - Source Code

So, as you may know harmonic series implies:


In this program, we take the integer value of n from the user and display the sum of the series according to this value. I just used a for loop, although there are many other ways to do the same.

Here is the code:
#include <stdio.h>
#include <conio.h>

int main()
{
     int n,i;
     float inverse;
     double sum=0.0;
     //Preliminary
     printf(\"Program to find:\\n\");
     printf(\"\\n   1    1    1    1          1\\n\");
     printf(\"  __ + __ + __ + __ + ... + __\\n\");
     printf(\"\\n   1    2    3    4          n\\n\");

     //Prompting for the value for 'n'

     printf(\"\\n\\nEnter the value of n: \");
     scanf(\"%d\", &n);

     //Iterating and summing

     for(i=1; i<=n; i++)
     {
         inverse = (1.0/i);
         sum += inverse;
     }
 
     //Displaying the answer

     printf(\"\\nRequired sum is %f\", sum);
 
     getch();
     return 0; 
}

Here is the output:

Happy Coding!
:)

Wednesday, 4 June 2014

Collatz Conjecture - Implementation in Java

Let's begin with a short intro to Collatz Conjecture*. It's also known in the names (3n+1) conjecture, Hasse's Algorithm, Syracuse problem, and a ton of others I really have a hard time remembering. The problem can be represented as a mathematical function as given below, which is iterated until the value of variable is reduced to 1.


The proposal of Collatz conjecture, is that, no matter what number you start with, you will eventually, at some point, reach 1. We all know that computers are especially good at repeating stuff! For this reason, many mathematicians, and computer scientists rely upon algorithms and computers to test these kind of problems. There is a lot of underlying math to this problem, some of which you can see at Wikipedia, and Wolfram Alpha. I'm not going into the math. Here is the code:


/* Implementation of Collatz Conjecture/ Hasse's Algorithm/ Syracuse Problem in Java using Recursion */
import java.util.Scanner;

public class CollatzConjecture {
    public static void Collatz(int x) {
        System.out.print(x + ", ");
        if (x == 1) {
           return; 
           // If x is 1, then the function is terminated
        } 
        else if (x % 2 == 0) {
           Collatz(x / 2);       
           // If x is even, then function is called with the argument x/2
        } 
        else if (x % 2 != 0) {
           Collatz((3 * x) + 1); 
           // If x is odd, then function is called with the argument 3x+1
        }
    }

    public static void main(String[] args) {
       System.out.print("Collatz Conjecture");
       System.out.print("\nEnter the starting number: ");
       Scanner in = new Scanner(System.in);
       int n = in.nextInt();
       Collatz(n);
       in.close();
   }
}

I have used recursion to carry out the iteration, you may also use any loop of your choice.
Here is a sample output. As you can see, even a number as small as 27 takes 111 steps to reach unity, and it touches a number as large as 9232 on its way!

27 reaches unity, taking 111 steps, touching the maximum 9232 on its way!


Don't jump into conclusions though. Specific numbers, as large as 1024, takes only 10 steps to reach 1. This is because 1024 is the tenth power of 2.

1024 reaches unity faster, because it is a power of 2


From these examples, it is safe to say that the number of steps taken is purely depended upon the nature of the number. Some numbers tend to reach 1 faster, and some takes a larger amount of time. This is the magic of Mathematics!

*Conjecture - An unproved proposition
Happy Coding!
:)

Friday, 30 May 2014

Project Euler : Problem #2 - C++ Solution

This time, the problem is:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I'm using a do-while loop here. Here is the code:
#include <iostream>
using namespace std;

int main()
{
    int a = 0, b = 1;
    int c, answer = 0;
    do{
        c = a + b;
        a = b;
        b = c;
        if(b%2==0){answer = answer + b;}
    }while(b<=4000000);
    cout<<"Answer is "<<answer;
    return 0;
}

Thursday, 1 May 2014

Project Euler : Problem #1 - C++ Solution


I was recently wandering around the internet, and I found out this awesome website, with some great mathematical problems which has to be solved using any programming language. You can easily get into the website by searching for "Project Euler" on Google. It has a great set of problems, to sharpen your problem solving skills in any programming languages. Here I'm posting the solution to the first problem. I will try to continue to give more solutions to more problems.

The problem is :

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
First go ahead an try to solve it on your own, and then refer the solution.
The solution to the problem is given below:


#include<iostream>
#include "conio.h";
using namespace std;
int main()
{
    int i;
    int result = 0;
    for(i=0;i<1000;i++)
    {
          if( i%3==0 || i%5==0 )
          {
                result = result + i;
          }    
    }
    cout<<"The answer is "<<result;
    getch();
    return 0;
}

Here is the output:

 :)

Tuesday, 11 March 2014

Signing off... (for a while)

Heyyyyy! Just staying away from the computer for a while (exams...).. Will be back in some days!

Code the world away guys!!!
 :)

Monday, 10 March 2014

Date Calc - Software Free Download!

Here is the software, the source code of which I had posted recently on this blog (here).

You can download the file from these links:

  • As .exe file  -   from here
  • As .rar file   -   from here

    Please give us your feedback by commenting below to keep us motivated!

Trace of a square matrix - C++ Program source code

Trace of a square matrix is the sum of elements of the principal diagonal of the matrix.

So without any intro, let's move on to code:
Code:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    int mat[100][100],tr=0,i,j,m,n;
    cout<<"Enter the order of the matrix : \n";
    cin>>m>>n;
    while(m!=n){
        cout<<"Not a square matrix!\n";
        exit(0);
    }
    cout<<"Enter the elements of the matrix : \n";
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            cin>>mat[i][j];
        }
    }
    cout<<"The matrix is : \n";
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            cout<<mat[i][j];
            cout<<"\t";
        }
        cout<<endl;
    }
    for(i=0;i<m;i++){
        for(j=0;j<n;j++){
            if(i==j){
                tr = tr + mat[i][j];
            }
        }
    }
    cout<<"The trace is "<<tr;
}

Working:
First we input the order of the matrix. If number of columns is not equal to number of rows, the matrix is not a square matrix and will not have a trace. So if they aren't same, the program terminates using exit(0) [in the header <cstdlib>]. Now inside a nested for loop, if an element is on the principal diagonal, then the trace tr, initially set to zero, adds itself to the element. At the end of the loop, tr will be equal to the sum of diagonal elements. 
A couple of sample outputs is given below:




Happy Coding!
:)


You might also like