Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Average in Bash

Problem

Given N integers, Show the average of N integers with 3 decimal places.

Input Format
La primera linea contiene The first line contain N integers.N lines with only one number.

Output Fromat
The integer with 3 decimal places.

Example


Input

4
1
2
9
8

Output

5.000


Code

read a
b=0
for (( c=1; c<=$a; c++ ))
do
read d
b=$(($b+$d))
done
echo $(printf %.3f $(echo "scale=4;($b/$a)" | bc))

Odd numbers in bash using a loop

Lately I've been kind of bored so instead of playing I've been entertaining myself by solving programming problems, one very easy this one.

Show the odd numbers from 1 until 99 using bash

code

for i in {1..99}
do
if(( $i % 2 != 0 ))
then
echo "$i"
fi
done

How many primes less than or equal to n exists?

In hackealo.co there was another problem and Ruby's solution was easier than I expected
How many primes less than or equal to 7293 exits?

#!/usr/bin/env ruby
require 'mathn'
s=0
Prime.each(7293) do |prime|
     s+=1
end
puts 'resultado:'+s.to_s

source


Ruby online
Prime numbers in Ruby

Using srand y rand in C

This semester I need to do code something using C and I don't remember much, I needed to generate random numbers and we know that "Random" isn't random at all in C, using rand() the numbers are going to repeat but using srand() we can get true random numbers, basically we need to change the "seed" inside the rand() using srand(), for this I'm going to use the time. I tested this code on Debian.

Code


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
int x;
  srand (time(NULL));
  for (x=0;x < 10; x++)
  {
    printf ("Numero: %d\r\n", rand() ); 
  }
  return 0;
}
PD: If you guys comment the line of the srand we can see the difference.