Maths – Pro9ramming https://pro9ramming.com Software craftsman's blog Wed, 15 Apr 2020 17:51:07 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 Python Powerball number generator https://pro9ramming.com/python-powerball-number-generator/ Wed, 16 Aug 2017 14:51:40 +0000 http://pro9ramming.com/blog/?p=489 Continue reading Python Powerball number generator]]> http://openbookproject.net/pybiblio/practice/wilson/powerball.php

Description
To win the Powerball lottery (an extremely unlikely event so don’t waste your time) you have to pick six numbers correctly. The first five numbers are drawn from a drum containing 53 balls and the sixth is drawn from a drum containing 42 balls. The chances of doing this are 1 in 120,526,770. Write a program to generate a set of Powerball numbers by utilizing the choice function in Python’s random module.

Input
Ask the user how many sets of Powerball numbers he or she would like.

Output
The program will print each set of Powerball numbers in numeric order.

Sample session
Official (but fruitless) Powerball number generator

How many sets of numbers? 3

Your numbers: 3 12 14 26 47 Powerball: 2
Your numbers: 1 4 31 34 51 Powerball: 17
Your numbers: 10 12 49 50 53 Powerball: 35

from random import randint
def BubbleSort(l):
    e=0
    for i in range(len(l)-1):
        for j in range(len(l)-1):
            if l[j]>l[j+1]:
                e=l[j+1]
                l[j+1]=l[j]
                l[j]=e
    return l
def MyPrint(L,pb):
        BubbleSort(L)
        print "Your numbers: %d %d %d %d %d Powerball: %d"%(L[0],L[1],L[2],L[3],L[4],pb)

print "Official (but fruitless) Powerball number generator"
No=int(raw_input("How many sets of numbers? "))
for i in range(No):
    numbers=[]
    powerball=randint(1,42)
    i=0
    while (i!=5):
        numbers.append(randint(1,53))
        i+=1
    for i in range(len(numbers)-1):
        for j in range(len(numbers)-1):
            if i==j:
                j+=1
            if numbers[i]==numbers[j] or powerball==numbers[j]:
                numbers[j]=randint(1,53)
                j-=1
    MyPrint(numbers,powerball)

Few notes:
After you choose how many sets of numbers you want, the first ‘while’ loop gives some random numbers to our powerball list. After that, the 2 ‘for’ loops check if we have double numbers in our list. Because after we draw one ball, that one cannot be chosen again and it is out of the game.

Then the process repeats for the rest of the sets.

]]>
Sum of even numbers https://pro9ramming.com/sum-of-even-numbers/ Tue, 20 Dec 2016 07:53:55 +0000 http://pro9ramming.com/blog/?p=385 The task is to create a program that sums all even numbers from 1 to n. If number modulus by 2 is equal to zero than that number is even (k mod 2 = 0). n is a parameter (from standard input).

Pascal solution:

program even_nums_sum;
var i,n,s:integer;
begin
    readln(n);
    s:=0;
    for i:=1 to n do
    begin
        if i mod 2 = 0 then
        begin
            s:=s+i;
        end;
    end;
    writeln(s);
    readln();
end.

]]>
Russian peasant multiplication method https://pro9ramming.com/russian-peasant-multiplication/ Wed, 16 Dec 2015 14:37:46 +0000 http://pro9ramming.com/blog/?p=427 Continue reading Russian peasant multiplication method]]> Russian Peasant multiplication (sometimes called “Ethiopian multiplication” or “Ancient Egyptian multiplication“)  is an interesting multiplication method that can be used to multiply large numbers (without overflow).

This task is interesting because different bitwise operators can be used while writing an algorithm in C++:

int a = 86, b = 57, product = 0;
while (b)
{
if (b & 1)
product += a;
a <<= 1;
b >>= 1;
}
cout << product;
cout << "\n";

First of all “while (b)” actually means “while (b!=0)”. (b & 1) is actually a check if number is odd. And << and >> are shifting operators which effectively give the result of integer multiplication and division respectively.

The solution can be written even more short by using for loop and ternary operator:

int a,b,product = 0;
for(;b;product+=(b&1?a:0), b>>=1, a<<=1);
cout << product;
cout << "\n";

 

 

]]>
Distance between two geographical points in PHP https://pro9ramming.com/distance-between-two-geographical-points-in-php/ Sat, 21 Feb 2015 21:43:27 +0000 http://pro9ramming.com/blog/?p=253 Continue reading Distance between two geographical points in PHP]]> This function returns distance in km or miles between two geographical points. Because of the near-spherical shape of the Earth (technically an oblate spheroid), calculating an accurate distance between two points requires the use of spherical geometry and trigonometric math functions. However, you can calculate an approximate distance using much simpler math functions (for example with Euclidean distance). For many applications the approximate distance calculation provides sufficient accuracy with much less complexity. The following approximate distance calculations are relatively simple, but can produce distance errors of 10 percent or more. These approximate calculations are performed using latitude and longitude values in degrees.
But this is only for purposes of fast PHP calculation so here is the code:

<?php
function getDistance($a_lat,$a_lng,$b_lat,$b_lng,$mi=false){
    var $radius;
    ($mi ? $radius=10253 : $radius=6371);
    $a_lat = deg2rad($a_lat);
    $a_lng = deg2rad($a_lng);
    $b_lat = deg2rad($b_lat);
    $b_lng = deg2rad($b_lng);
    if($a_lat==$b_lat && $a_lng==$b_lng) return 0;
    if ((sin($b_lat)*sin($a_lat ) + cos($b_lat)*cos($a_lat )*cos($b_lng-$a_lng))>1)
        return $radius * acos(1));
     return $radius * acos(sin($b_lat)*sin($a_lat)+cos($b_lat)*cos($a_lat)*cos($b_lng-$a_lng)));
}
?>

 

 

]]>
Binary GCD Algorithm https://pro9ramming.com/binary-gcd-algorithm/ Tue, 02 Dec 2014 12:43:27 +0000 http://pro9ramming.com/blog/?p=226 This is an interesting algorithm for finding the greatest common divisor.

Euclid Algorithm that does the same thing (more here).
Except Euclid Algorithm, Binary Algorithm is used, more on wiki.
C++ code:

# include <iostream>
# include <cstdio>

using namespace std;

int gcd(int u,int v)
{
     int s;
     if (u == 0 || v == 0)
       return u | v;
     for (s = 0; ((u | v) & 1) == 0; ++s) {
         u >>= 1;
         v >>= 1;
     }
     while ((u & 1) == 0)
       u >>= 1;
     do {
         while ((v & 1) == 0) 
           v >>= 1;
         if (u < v) {
             v -= u;
         } else {
             int diff = u - v;
             u = v;
             v = diff;
         }
         v >>= 1;
     } while (v != 0);
     return u<<s;
}

int main()
{
    int a,b;
    cin>>a;
    cin>>b;
    cout<<gcd(a,b)<<endl;
    system("pause");
}

 

]]>
Definite integral https://pro9ramming.com/definite-integral/ Tue, 25 Nov 2014 09:43:27 +0000 http://pro9ramming.com/blog/?p=60 Task is to create a program that determines a definite integral of the function f(x)=sin(x)*ln(x), where bounds are given by real parameters A and B (segment of Ox). That basically means that you have to calculate the area under the function.

Here is the solution in TPW:

program integral;
uses wincrt;
const dx = 0.0001;
var
  i,a,b,p:real;
  label top;
begin
top:
writeln('Enter start of segment of Ox !');
readln(a);
repeat
begin
writeln('Enter end of segment of Ox !');
readln(b);
end;
until b>a;
i:=a+dx;
p:=0;
repeat
begin
  p:=p+abs(dx*sin(i)*ln(i));
  i:=i+dx;
end;
until i>b;
writeln('Solution is ',p:9:4);
writeln('Press Enter to try again !');
readln;
clrscr;
goto top;
end.

 

]]>
Separate digits from integer number https://pro9ramming.com/separate-digits-from-integer-number/ Tue, 25 Nov 2014 07:43:27 +0000 http://pro9ramming.com/blog/?p=91 Continue reading Separate digits from integer number]]> If you have to find sum of integer’s digits, then use this algorithm is essential. In TPW there are no standard functions as strtoint() and inttosr() as in Delphi. You can easily do this in Delphi with this functions. But in Pascal there is a way to do this without this functions with “mod” and “div” operators.
These functions can be easily understood from this example:

5 div 2 = 2
5 mod 2 = 1

If you get the modulus of a number when divided with 10, you would get last digit, than you can divide it by 10 and do modulus again till you reach zero.

Here is the implementation in TPW:

program cut_digits_out_of_number;
uses wincrt;
var
  n:longint;
  i,j:integer;
  a:array [1..100] of integer;
begin
writeln('Program for cutting digits');
writeln('out of an integer number !');
writeln('Enter integer number !');
readln(n);
i:=0;
repeat
begin
   i:=i+1;
   a[i]:=n mod 10;
   n:=n div 10;  
end;
until n=0;
writeln('Digits are : ');
for j:=i downto 1 do
writeln(a[j]);
end.

But if you want to use function like in Delphi strtoint(), you can make it in Pascal. Like i made it. And i used string cutting and i made that function, so solution looks like this:

program cut_digits_out_of_number;
uses wincrt;
var
  n:string;
  i:integer;
  a:array [1..100] of integer;
function numcheck(s: string): boolean;
var
  x:integer;
begin
numcheck:=true;
for x:=1 to length(s) do
  if (ord(s[x])<48) or (ord(s[x])>57) then
   if s[x]<>'' then
    numcheck:=false;
end;
function str_to_int(s:string):integer;
var
  check:integer;
  i:integer;
begin
   if numcheck(s) then
    val(s,i,check);
   str_to_int:=i;
end;
begin
writeln('Program for cutting digits');
writeln('out of an integer number !');
writeln('Enter integer number !');
readln(n);
for i:=1 to length(n) do
begin
a[i]:=str_to_int(n[i]);
end;
for i:=1 to length(n) do
writeln(a[i]);
end.

Or you can use val procedure, explained in Help:

valprocedure

]]>
Easiest problem with matrices https://pro9ramming.com/easiest-problem-with-matrices/ Sat, 15 Nov 2014 23:43:27 +0000 http://pro9ramming.com/blog/?p=144 The task is to read a matrix and than write it out on a screen (output).

TPW code:

program matrix_read_write;
uses wincrt;
var
  a:array[1..100,1..100] of integer;
  i,j,m,n:integer;
begin
writeln('Enter length of matrix !');
readln(n);
writeln('Enter height of matrix !');
readln(m);
for i:=1 to n do
  for j:=1 to m do
    read(a[i,j]);
for i:=1 to n do
  begin
    writeln;
  for j:=1 to m do
    write(a[i,j],' ');
  end;
end.

 

]]>
Eternal Calendar https://pro9ramming.com/eternal-calendar/ Wed, 12 Nov 2014 07:43:27 +0000 http://pro9ramming.com/blog/?p=111 This is the code for Eternal calendar that works for AD only and till year 4000:

program calendar;
uses wincrt;
type
  months=1..12;
  dayinweek =0..6;
var
  days:array[months] of integer;
  month,year:integer;

  function leapyear(year:integer):boolean;
  begin
  if (year mod 100)=0 then
  leapyear :=(year mod 400) = 0
  else
  leapyear := (year mod 4) = 0
  end;

  function firstjanuary(year:integer): dayinweek;
  begin
  firstjanuary := (year+(year-1) div 4-(year-1) div 100 +(year-1) div 400 ) mod 7
  end;

  procedure setdays (year:integer);
  begin
  days[1]:=31;
  if leapyear(year) then
  days[2]:=29
  else
  days[2]:=28;
  days[3]:=31;
  days[4]:=30;
  days[5]:=31;
  days[6]:=30;
  days[7]:=31;
  days[8]:=31;
  days[9]:=30;
  days[10]:=31;
  days[11]:=30;
  days[12]:=31;
  end;

  function firstdayinmonth (month,year:integer): dayinweek;
  var
  i,brdana:integer;
  begin
  setdays (year);
  brdana :=0;
  for i:=1 to month-1 do
  brdana:= brdana + days[i];
  firstdayinmonth := (firstjanuary (year) + brdana) mod 7;
  end;

  procedure writing (month,year :integer );
  var
  i,n:integer;
  begin
  writeln;
  writeln('==================================');
  write('Calendar for ',month,'. month ');
  writeln (year,'. year');
  writeln ('----------------------------------');
  writeln (' Sun Mon Tue Wed Thu Fri Sat');
  n:=firstdayinmonth(month,year);
  for i:=0 to n-1 do
  write ('    ');
  for i:=1 to days[month] do
  begin
  write (i:4);
  n:=n+1;
  if (n mod 7) =0 then
  writeln;
  end;
  writeln;
  writeln;
  end;

  begin
  repeat
  write (' Enter month : ');
  readln (month);
  until (month>=1) and (month<=12);
  repeat
  write (' and year : ');
  readln (year)
  until (year>=0) and (year<= 4000);
  writing (month, year);
  Writeln;
  end.

 

]]>
Function area https://pro9ramming.com/function-area/ Wed, 12 Nov 2014 04:43:27 +0000 http://pro9ramming.com/blog/?p=169 Continue reading Function area]]> This is simple program for finding area under the sin() function. All mathematicians know that area under the function is integral of that function. But you need to know segment on Ox where you want to find area. But algorithm for finding integral of function is complicated, and heavy to write, and if i post that everybody would have face like this Angry, so if you want to find integral of function, you can do it here:
http://integrals.wolfram.com/index.jsp
To continue, we all know that area of rectangle is a*b.
But in coordinate system it is x*y and y represents solution of function, so it is x*f(x), but if function changes on every x, that x must be small number to get that area accurately so it is 0.0001, and you can have it even more small, and accuracy would be better.
f(x) in this case is sin(x) and i called that small number dx=0.0001.
so surface of one small sqare of sin() function is dx*sin(x).
And of segment from a to b is sum of all that rectangle surfaces between a and b. But if function goes under 0 in minus.
Then you need to use absolute value:

p:=p+abs(sin(i)*dx);

And input is segment between a and b. Parameter b has to be bigger than a.
For example, if pi=3.141, if you enter segment from 0 to pi, you’ll get solution 2, because that area is 2, as you can see in the picture:

integrals

Code in TPW:

program find_surface_of_function_sinx;
uses wincrt;
const dx = 0.0001; 
var
  i,a,b,p:real;
begin
writeln('Program for finding area in segment of sin() function');
writeln('Enter start of segment of Ox');
readln(a);
repeat
begin
writeln('Enter end of segment of Ox');
readln(b);
end;
until b>a;
i:=a+dx;
p:=0;
repeat
begin
  p:=p+abs(sin(i)*dx);
  i:=i+dx;
end;
until i>b;
writeln('Solution is ',p:9:4);
end.

 

]]>