Another C mathematical program

Disclaimer: For the non geeky programming lovers out there, sorry for spamming you with this bunch of incomprehensible lines of text!

The first time I wrote some kind of program was back in high school with a Ti80 calculator which had some sort of BASIC programming language. After reading the manual I spent hours making small mathematical programs to speedup my problem solving study. I must say the programs were not that useful to math because in the tests I had of course to show all the calculation I did… Then I forgot most things about programming… Until some years ago :) .

Anyways, what does this have to do with the code below? Almost nothing! The code bellow calculates the mode of n numbers provided by a user. It dynamically creates an n size array and checks with value is seen more often. I still haven’t done a python version this time, if someone wan’ts to do it in python or any other language, please do! :D

Here it goes.

#include <stdio.h>
#include <stdlib.h>
 
/*Create a n sized array*/
int* makearray(int n)
{
    int* v;
    int i;
 
    v = (int*) malloc(n*sizeof(int)); /*Alocates n int numbers*/
    printf("Array elements:\n");
    for (i = 0; i < n; i++){ /*Fill the array with user input*/
        scanf("%d", &v[i]);
    }
 
    return v;    
}
 
/*Get the size of an array*/
int arraylen(int v[])
{
    int i=0;
    while(v[i]) i++;
    return i;
}
 
/*Count how many times a given element is repeated in an array*/
int countelem(int v[], int num)
{
    int i, n=0;
 
    for (i=0; i < arraylen(v); i++){
        if (v[i] == (int) num){
            n++;
        }
    }
    return n;
}
 
int main()
{
    int n, i, count = 0, mode;
    int* v;
 
    printf("Size of the array?\n");
    /*We don't wan't anyone creating a oversized array: DANGER'*/
    /*So we limit it's' size. Here I randomly defined 100*/
    do{
        scanf("%d", &n);
 
    } while(n > 100);
 
    v = makearray(n);
    /*Update the wich value is repeated more ofted -> Mode*/
    for (i = 0; i < n; i++){
        if (countelem(v, v[i]) > count){
            count = countelem(v, v[i]); /*Update the value of the maximum number of repeats*/
            printf("%d\n", count);
            mode = v[i]; /*Update mode*/
        } 
 
 
    }
 
    printf("Mode: %d\n", mode);
    return 0;
 
}

EDIT: There was a little bug with my code, it’s fixed now :) .

One of my colegues made a python version :D . Hope he doesn’t mind if I publish it :)

#!/bin/sh python
#-*- coding: utf-8 -*-
 
 
def makearray(v):
  """Creates the dictionary with the elements input by the user
  """
  print "Array elements (end with empty line):"
  while(1):
    s = raw_input("-> ")    # get an element
    if not s:
      break
    try:
      i = int(s)
      if v.has_key(i):      # if already exists, increment frequency
        v[i] += 1
      else:                 # if not, create it
        v[i] = 1
    except:                 # error handling
       print "not an integer"
 
 
#-----------------------------------------------------------------------
# program
 
# instead of a vector or array, we do this with a dictionary
# that way we can keep the frequency count with each entry
v = {}
makearray(v)
 
# get the mode
if len(v):
  mode = 0
  maxfreq = 0
 
  for i in v.keys():
    if v[i] > maxfreq:
      mode = i
      maxfreq = v[i]
 
  print "Mode %d, with frequency %d" % (mode, maxfreq)
 
else:
  print "Empty array"

Technorati Tags: , , ,

Prime factors code in C and Python

Today someone spoke about prime factors and I thought it was something interesting to code. I needed to practice my C so I’ve coded it in C. Here it goes:

#include <stdio.h>
#define VMAX 25
 
int main()
{
    /*Prime numbers < 100 */
    int primes[VMAX] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
    int factors[VMAX] = {}; /*Prime factors*/
    int repeat[VMAX] = {}; /*Store times each factor repeats*/
    int a, i, n=0;
 
    printf("Type a number to find it's prime factors: \n");
    scanf("%d", &a);
 
    /*Start to divide the number by prime numbers while a is not 1*/
    for (i=0; i<VMAX; i++){
        while ((a != 1) && (a % primes[i] == 0)){ 
 
            a = a / primes[i];
            factors[i] = primes[i]; /*The prime factor is the one being used*/
            n++; /*Count how many times each prime is used*/
            } 
        if ((a % primes[i] == 0) ) n = 0; 
        repeat[i] = n;
        n = 0; /*Reinitialize counter*/
 
    }
    printf("Prime factors:\n");
    for (i=0; i<VMAX; i++){
 
        /*Print all factors in the array != 0*/
        if (factors[i] !=0){
            /*Since x ^ 0 = 1, we have to print x ^ 1 instead*/
            if (repeat[i] == 0) printf("%d ^ 1\n", factors[i]);
            else printf("%d ^ %d\n", factors[i], repeat[i]);
        }    
    }       
 
    return 0;
 
}

I really like python but unfortunately I haven’t had the time to code anything with python. Now it’s learning C , then C++ and so on. But this time I wanted to code this in python also. I’m a bit out of practice and my brain was thinking in C. But here it goes.

#! /usr/bin/env/python
VMAX = 25
 
#Prime numbers < 100
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
factors = [0]*VMAX #Prime factors
repeat = [0]*VMAX #Store times each factor repeats
i = 0
n = 0
k = 0
 
a = raw_input("Type a number to find it's prime factors:")
 
#Start to divide the number by prime numbers while a is not 1
for i in range(VMAX): 
 
    while ((a != 1) & (int (a) % primes[i] == 0)):
 
        a = int (a) / primes[i]
 
        print primes[i]
        factors[i] = primes[i] # The prime factor is the one being used
 
        n = n + 1 #*Count how many times each prime is used
        print n
    if (int (a) % primes[i] == 0):
        n = 0 #Reinitialize counter
    repeat[k] = n
    n = 0
    k = k + 1
 
print "Prime factors:"
 
#Print all factors in the array != 0
for i in range(VMAX):
 
    if (factors[i] !=0):
    #Since x ^ 0 = 1, we have to print x ^ 1 instead
        if (repeat[i] == 0):
            print factors[i]
        else: print "%s ^ %s " % (factors[i], repeat[i])

Technorati Tags: , , ,

Breathing more now, but not for long

The last few days have been just a tiny bit more quiet and I can finally have *some rest at night. I like being busy but the last weeks have been ridiculous. In a few days work will catch up and take my time away again. Plus I have to study some more for the exams. The good part is that I have some work already done so I think I won’t have to work till very late.

Apart from work and boring stuff, I went with the flow and finally signed up for facebook. I was quite septic but I must admit it was a pleasant surprise.

I’ve discovered, thanks to a University college in facebook a really great site to discover music:  thesixtyone . Check it out.

I’m trying out gnome-shell with the new message tray, pretty cool :) Check it out as well! I just hope Xorg doesn’t lock on me with KMS…

Bye!

Technorati Tags: , , ,

Random

I haven’t been much of a blogger lately. I’ve been really busy with life to come here and type a couple of lines. However some times we really need to make some sacrifices to achieve something we aspire to. Right  now I’m just procrastinating because numbers are not being very friendly to me. I’d rather be watching 30 rock, surfing the web, or something else I do for fun, but right now I need to concentrate and get back to work.

Cya.

Technorati Tags: