Project Euler – Problem 2
June 11, 2012 at 10:14 am | Posted in Programming | Leave a commentTags: Project Euler, project euler solutions
I mentioned Project Euler in my previous post. Next problem was little bit hard to do and I rewrote my code 3 times before I got it right:
/* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*/
#include <stdio.h>
unsigned long fib(unsigned long num);
int main(void)
{
const unsigned long limit = 8;
unsigned long sum = 0;
unsigned long i = 0;
for(i = 0; i <= limit; ++i)
{
unsigned long j = fib(i);
if(0 == (j % 2))
{
sum += j;
}
}
printf("Sum of all Fibonaci even numbers upto %lu = (%lu)\n", limit, sum);
return 0;
}
unsigned long fib(unsigned long num)
{
unsigned long temp = 0;
if((0 == num) || (1 == num))
{
temp = 1;
}
else
{
temp = fib(num - 1) + fib(num - 2);
}
return temp;
}
What can you see from above code. I got the meaning of problem statement totally wrong. Problem says “I need to add all Fibonacci numbers with values upto 4 million” whereas I took it as “add all numbers upto 4 million as input to Fibonacci”. 2nd, What else is wrong ? Can you spot it ? Stop reading right now and run this in your compiler. If you have gcc then please use -ansi -pedantic -Wall -Wextra flags. Go ahead and try and come back again. This program keeps on running for 11 minutes when limit is 400. The recirsive call eats all CPU. Even after 11 minutes I killed it. My machine is quite average in terms of hardware. Imagine at 4 million as input, how many years it will take to complete ? So what do we do ? First we get our brains right that it requires us to add all Fibonacci values less than 4 millions. 2nd, we will not use recursion and instead we will make use of the fact that F(N) = F(N-1) + F(N-2) provided F(0) = F(1) = 1, where F is fibonacci for N. We can rememeber last two fibonacci numbers in some variables instead of using recursion to find out every time. Recursion uses a lot of stack and I don’t think you should assume that you will have stack for 4 millions. Here is the correct and new iterative version.
/* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*/
#include <stdio.h>
int main(void)
{
const unsigned long limit = 4000000;
unsigned long sum = 0;
unsigned long i = 0;
unsigned long f = 1; /* Fibonacci(0); */
unsigned long f2 = 1; /* Fibonacci(0); */
unsigned long f1 = 1; /* Fibonacci(1); */
for(i = 2; f <= limit ; ++i)
{
/* In first iteration, Fibonacci(2) = F(1) + F(0) */
f = f1 + f2;
if(0 == (f % 2))
{
sum += f;
}
f2 = f1;
f1 = f;
}
printf("Sum of all Fibonaci even numbers upto %lu = (%lu)\n", limit, sum);
return 0;
}
I still see something wrong with above code. Did you notice several issues ? Don’t just read ahead, read the code and see how it fits problem statement. Its using <= instead of < . Problem statement says “upto 4 millions” and that does not include 4 millionth term (##c on freenode correct me on this as I am not a native English speaker. I thought “upto” included 4 millions). Other problem is using iteger i. We are not iterating for a specific number of times but till a certain condition is reached without caring how many times we iterated. So we need to remove that counter.
/* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*
* My Method: F(n) = F(n-1) + F(n - 2) (where F(0) = F(1) = 1)
* find the sum of all values where F(n) is even, till 4 million
*
*/
#include <stdio.h>
int main(void)
{
const unsigned long limit = 4000000;
unsigned long sum = 0;
unsigned long f = 0; /* Fibonacci(0); */
unsigned long f2 = 0; /* Fibonacci(0); */
unsigned long f1 = 1; /* Fibonacci(1); */
while((f1 < limit) && (f2 < limit))
{
/* In first iteration, F(2) = F(1) + F(0) */
f = f1 + f2;
if(f >= limit) break;
if(0 == (f % 2))
{
sum += f;
}
f2 = f1;
f1 = f;
}
printf("Sum of all Fibonaci even numbers upto %lu = (%lu)\n", limit, sum);
return 0;
}
How long it takes to execute. As per ideone.com , it take 0.02 seconds. And I was waiting for 11 minutes for the first piece of code. How much good programming practice is worth of ? a few thousands extra in salary of the programmer, a millions for the bugs caused or the entire bank account multi-billioon dollor corporation if it hires all bad programmers ? What do you think ?
Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)
Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.
Code from IBM
June 4, 2012 at 3:28 pm | Posted in Uncategorized | Leave a comment
I got the job to fix Segmentation Fault somewhere. While I was searching for strftime(), localtime(), ctime() , localtime_r() etc and their behavior with with multi-threaded programs (POSIX threads), I came across this piece of code from IBM. you can find it here if its still available. I have a screenshot too
#include <stdio.h>
#include <time.h>
int main(void)
{
char s[100];
int rc;
time_t temp;
struct tm *timeptr;
temp = time(NULL);
timeptr = localtime(&temp);
rc = strftime(s,sizeof(s),"Today is %A, %b %d.\nTime: %r", timeptr);
printf("%d characters written.\n%s\n",rc,s);
return 0;
}
/*************************************************
The output should be similar to:
46 characters written
Today is Wednesday, Oct 24.
Time: 01:01:15 PM
************************************************************/
This C program is not correct. Do you see anything wrong with code ? What is it ? Do you see anything wrong with calls of localtime() and strftime() ? Return values from them are not checked:
- localtime():
- strftime():
Returns NULL when some error occures. You pass this NULL to strftime() and whoaaa.. you got undefined behavior.
Even if localtime() behaved correctly strftime() can return with an error condition. IBM’s code does save return value but again does no check of it. Program is simply printing array passed to strftime() without checking if return value was zero or not. Man page of strftime() says:
The strftime() function returns the number of characters placed in the array, not including the terminating null byte, provided the string, including the terminating null byte, fits. Otherwise, it returns 0, and the contents of the array is undefined. (Thus at least since libc 4.4.4; very old versions of libc, such as libc 4.4.1, would return max if the array was too small.)
Now if the contents of array are undefined then behavior of program is undefined too because you are trying to print an array with undefined contents. It can cause crash (if you are lucky), it can print garbage (you are still lucky) or it can just work fine printing the time because most of the time there will no error and that is utter badluck because definitely it will crash on first run when client is using it (trust me, its very ususal). So what we do ? Just two simple checks and client will be happy and that includes your happiness too. Here is the fixed code:
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t temp;
struct tm *timeptr;
temp = time(NULL);
timeptr = localtime(&temp);
if(NULL == timeptr)
{
printf("Error localtime()\n");
}
else
{
int rc;
char s[100] = {0};
rc = strftime(s,sizeof(s),"Today is %A, %b %d.\nTime: %r", timeptr);
if(0 == rc)
{
printf("Error strftime()\n");
}
else
{
printf("%d characters written.\n%s\n",rc,s);
}
}
return 0;
}
/*************************************************
Compiled on Linux:
/home/arnuld/programs/C $ gcc -std=c99 -pedantic -Wall -Wextra ibm.c
/home/arnuld/programs/C $ ./a.out
43 characters written.
Today is Monday, Jun 04.
Time: 03:50:57 PM
/home/arnuld/programs/C $
************************************************************/
There is one more change. I have put varibales in closest possible block (check out int rc and char s, it is because I don’t see the point of decalring them earlier and using them later. Local variables must be decalred/defined in the closest block possible. Another difference is I am initializing the array with null characters (or filling it with zeroes) so that it does not contain any garbage. This is actually more of a matter of style, a personal thing rather than a rule to write correct programs in C. It does write correct program and its not required that you do same while the first change regarding keeping variables in tightest scope possible definitely comes under one of the methods of writing good C programs.
Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)
Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.
Coding Horror
June 3, 2012 at 2:17 pm | Posted in art, Programming | Leave a commentTags: coding horror, f5 essential phone interview questions, Five Essential Phone-Screen Questions, steve yegge
Recently I was reading an article on coding horror which mentioned that most of the software developers who come for interview can’t even program and later I came across another article regarding phone screening interview and he mentioned Steve Yegge’s 5 essential phone screen questions. I looked at them and I thought .. whoaaa.. so easy. I was with my friend on his Windows machine and did not have access to some Linux machine. So I downloaded Bloodshed’s Dev-C++ compiler and typed this code and ran several tests, all in 20 minutes. (Bloodshed Dev-C++ version 5.2.0.2). I solved only several questions, will solve others when I get time to sit on machine next time. For now, just enjoy my C code
/* (1) Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the
number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
(2) Write function to compute Nth fibonacci number
(3) print all odd numbers between 1 and 99
*/
#include <stdio.h>
enum { LIMIT = 100 };
void fib(const int n);
void print_odds(const int limit);
void print_fizzbuzz(const int limit);
int main(void)
{
print_fizzbuzz(LIMIT);
printf("\n\n");
print_odds(LIMIT-1);
printf("\n\n");
fib(20);
return 0;
}
/* No int/unsigned-long overflow check */
void fib(const int n)
{
unsigned long f0 = 0;
unsigned long f1 = 1;
unsigned long fnum = f1;
int i;
if((0 == n) || (1 == n))
{
printf("fib(%d) = %d\n", n, n);
return;
}
for(i = 2; i <= n; ++i)
{
fnum = f1 + f0;
f0 = f1;
f1 = fnum;
}
printf("fib(%d) = %lu", n, fnum);
}
void print_odds(const int limit)
{
int i;
for(i = 1; i <= limit; i = i + 2)
{
printf("%d\t", i);
}
printf("\n");
}
void print_fizzbuzz(const int limit)
{
int i;
for(i = 0; i <= limit; ++i)
{
if((0 == i%3) && (0 == i%5))
{
printf("fizzbuzz\t");
}
else if(0 == i%3)
{
printf("fizz\t");
}
else if(0 == i%5)
{
printf("buzz\t");
}
else
{
printf("%d\t", i);
}
}
printf("\n");
}
Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)
Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.
Project Euler – Problem 1
May 28, 2012 at 3:23 pm | Posted in Programming | 2 CommentsTags: Project Euler
Recently I came across Project Euler. I always had trouble with applying problem-solving thinking to problems. Somone on IRC somwhere told me that these are the toughest problem he had ever faced in programming. I think its a good idea to test my abilities by solving these problems. Here is the first and easy one (easiest one ?):
/* Add all the natural numbers below one thousand that are multiples of 3 or 5.
* version 0.1
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i;
unsigned long s = 0;
for (i = 3; i < 1000; i += 3)
s += i;
for (i = 5; i < 1000; i += 5)
{
if(i % 3) s += i;
}
printf("%lu\n", s);
return EXIT_SUCCESS;
}
After you solve a problem and give correct answer, it shows in your registered account as solved and a link to the forum thread is also provided where you can see different kinds of solutions posted in different languages. It also shows how many people so far have solved the problem. Thats a good measure of your intelligence (if very few has solved it). Iam using C language for now to solve problems as C is the only language I know currently. I think you must go ahead and give Project Euler a try.
Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)
Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.
Go Programming Language
May 25, 2012 at 12:47 pm | Posted in community, Programming | Leave a commentTags: go programming language, google go, google go comparison with C, google go comparison with Haskell, haskell vs google go
I was reading draft of new C++ standard a.k.a C++11 (you too must check out N3337.pdf) and somehow I came across Go Programming Lanaguage and on that same page I found this quote of Bruce Eckel:
The complexity of C++ (even more complexity has been added in the new C++), and the resulting impact on productivity, is no longer justified. All the hoops that the C++ programmer had to jump through in order to use a C-compatible language make no sense anymore — they’re just a waste of time and effort. Now, Go makes much more sense for the class of problems that C++ was originally intended to solve.
Now thats a pretty solid and strong statement, I got shakes reading that and it reminded me of The Case for D by Andrei Alexandrescu. Go is designed by a team consiting of our good old friends Rob Pike and Ken Thompson. It has some very good positive reviews. I still have to read the criticizm of it. As per computer language shootout results, C (using GNU’s gcc) is far faster but the code-size of Go was much less (almost 1/3rd). Next on comparison was C++ (GNU’s g++) and results were almost same. Next on my list were Lisp and ATS. checkout the results yourself down here in graphs.
I discussed this performance issue on Go language IRC channel (#go-nuts, freenode) and they gave me very logical and accurate explanation that Go is not mature yet and performance comparison is with very mature C and C++ libraries which are around for a decade or more. So I cna conclude comparison is not exactly a fair comparison. I think Go will catch up with performance issues very fast as user base is growing at electric pace. Reminds me of the times and discussion when Python’s user base was growing and they were trying to resolve all the issues they could with full hard work.
Whenever a new language comes or whenever you want to learn an already established language, I think you must look into why that language was created in first place. Does that match your why of learning ? you must be using that language for some purpose, does the design goal suit your purpose ? In my case I think Go language suits, here is the excerpt from Does the world need another programming language ?
A couple of years ago, several of us at Google became a little frustrated with the software development process, and particularly using C++ to write large server software. We found that the binaries tended to be much too big. They took too long to compile. And the language itself, which is pretty much the main system software language in the world right now, is a very old language. A lot of the ideas and changes in hardware that have come about in the last couple of decades haven’t had a chance to influence C++. So we sat down with a clean sheet of paper and tried to design a language that would solve the problems that we have: we need to build software quickly, have it run well on modern multi-core hardware and in a network environment, and be a pleasure to use.
Go has the feel of a dynamic language like Python or Ruby or JavaScript, but it has the performance and safety of a language like Java or C or C++. So you get the lightweight feel of a modern scripting dynamic language but the robustness and performance of a more old-fashioned language.
Based solely on the above criteria I think I can start using Go right away and if I don’t have enough mature libraries or some specific functionality, then ATS is always there. When companies become big they become rigid, like a stubborn spoilt son of a businessman. They refuse to change to get edge over other software corporations because the change requires a lot of effort. I think the weight of word “Google” behind Go programming language will give it an edge over that rigidity. (same thinkg with Java and .NET).





Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)
Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.