Tuesday, December 13, 2016

Python 3 Prime Number Checker

Doing basic math is good exercise when working out the details of a programming language.
This one is using Python to check for prime numbers from 2 up to whatever value we have chosen. In this example, it is up to 50, but you can choose whichever value you wish.

This is using Python 3.
If you're transitioning from Python 2 you can use this acronym to remember the basic differences.

DRIP
Division is true division 2/3 = 1.5
Range is a generator, and there is no more xrange.
Items will help you get to Dictionary elements, you do not need iteritems
Print() is a function and no longer a statement. you need those parens
   if you want to not print a newline, 
   instead of a comma, you need to use end="" You can put a character in the ""


Prime Number Checker

max = 51
print ("Prime numbers up to", max)
for i in range(2,max):
    #skip evens
    if i % 2 == 0:
        # 2 is our first prime number, print it out
        if i == 2:
            print (i, end=" ")
        continue
    # check each value is divisible by 3 up to the value being checked itself. (from 3 -> the value in question
    # if the value being checked it 9 then check 3,4,5,6,7,8,9
    # we don't need to check using 2 because we already excluded the even numbers above
    evennum=False
    for k in range (3,i):
        if i % k == 0:
            evennum=True
            break
    if evennum==True:
        continue
    else:
        print(i,end=" ")

But wait~ There's more.
If a number is not prime then it has factors and for each two factors, one of them is below the square-root of the value you are checking. We only care if one of the factors exists (which will make the value not prime. As a result, we only have to check the values up to the "floor" (truncated integer) of the square-root of the value we're checking.

Example. Let's look at 36 which is not prime (we'll ignore that it's an even number and won't ever show up on our list.

  sqrt(36) = 6
36 has other factors
2x18
3x12
4x9

If we find even one of these factors we know it's not prime.
See how the factors distribute themselves around the squart-root
One is always lower and the other is always higher than 6.

So instead of for k in range (3, i)
we can do for k in range(3, math.floor(math.sqrt(i))
Since we're now doing math functions, we need to include the math module.

Here is a good reference (scroll down):
http://stackoverflow.com/questions/5811151/why-do-we-check-up-to-the-square-root-of-a-prime-number-to-determine-if-it-is-pr

Here's the full code:
import math
max = 51
print ("Prime numbers up to", max)
for i in range(2,max):
    #skip evens
    if i % 2 == 0:
        # 2 is our first prime number, print it out
        if i == 2:
            print (i, end=" ")
        continue
    # check each value is divisible by 3 up to the value being checked
    # we don't need to check using 2 because we already excluded the even numbers above
    # NOTE we only need to check if there's a factor up to the square-root of the series
    # (See the text for an explanation)
    endval = math.floor(math.sqrt(i))
    evennum=False
    for k in range (3,endval):
        if i % k == 0:
            evennum=True
            break
    if evennum==True:
        continue
    else:
        print(i,end=" ")



Thursday, October 20, 2016

Trump's Popularity Shows We Need Better Education in the US



The 2016 presidential campaign is nearing its end and for weeks, if not months, we've see how Trump can outright lie to his supporters. The many egregious moments (famous and too many to list) have cost him the election, but the number of moments were far above what would have cost another candidate the election. There is something that he is able to tap into that makes his fans mentally overlook his many flaws. Perhaps it is star power or just the pure chutzpah, but the fact that he can directly lie to his fans is disturbing.

Hillary says she wants to raise taxes on those making over $250,000.
Trump says to everyone: Hillary is going to raise your taxes.
And that's the most innocent example.

Bragging about sexual assault in general and then claiming that it never actually really happened (even if one incident has witnesses), is amazing.

You can say that that is a matter of opinion, but then he claims that he never said that climate change is a hoax perpetuated by the Chinese. Never mind that he tweeted about it more than once.

His most ardent supporters (there are fortunately fewer and fewer of them) are happy to ignore these shortcomings. No amount of facts seems to make any difference. His woeful ignorance on foreign policy and on basic things like how nuclear weapons work is just painful. His fans seem to have no filters. No inquisitive distance at all.

His presence in the election, and his popularity is casting a glaring light on the lack of education and educational opportunities in this country. Post-secondary education needs to be free, and the quality of the current free secondary education needs to be improved. Anyone with a high school diploma (even younger) should be able to discern that something is very wrong with Trump's many claims.

Sunday, August 14, 2016

The Fibonacci Sequence in Six (plus) Languages

The Fibonacci Sequence in Six (plus) Languages
Python, C, Java, Node.js, Javascript, Powershell

I wanted to write a blog post that shows how to generate the Fibonacci sequence (0;1;1;2;3;5;8;13;21;34;55;...) in ten languages. Then I realized I would have to relearn some older language's syntax and that would mess up my current knowledge. So this is now down to five languages.

You should see output like:
First 10 Fibonacci numbers
1
2
3
5
8
13
21
34
55

Some of the scripts put the numbers on one line.

I had to encode all the less than and greater than's to keep the browser from interpreting them.



Python 2
I ran this in my Mac terminal with: python fibo.py

# fibonacci series generator for the first 10 numbers

# Seeds 0 and 1

x=0
y=1

print "First 10 Fibonacci numbers"

for i in range(1,10):
  t = x + y
  x = y
  y = t
  print t






Python 3
Then I rewrote it all in Python 3, and it uses fancy tuple unpacking which avoids needing a temporary variable. Putting in the end=" " keeps the series all on one line.

# fibonacci series generator for the first 10 numbers
# using tuple unpacking
# for Python 3

# Seeds 0 and 1

x=0
y=1

print ("First 10 Fibonacci numbers")

for i in range(1,10):
  print (y, end=" ")
  x, y = y, (x+y)





C
You need to compile this with a C compiler.

#include <stdio.h>

int main () 
{
  int x=0;
  int y=1;
  int i,t;
  printf ("First 10 Fibonacci numbers\n");

  for (i=0;i<10;i++)
  {
    t = x + y;
    x = y;
    y = t;
    printf ("%d ",t); 
  }
  printf("\n");

  return (0);
}



Java
Probably should have it be more object oriented, but that doesn't save any lines in this case.
You do have to have the Java dev kit installed on your system.
#include <stdio.h>

int main () 

{
  int x=0;
  int y=1;
  int i,t;
  printf ("First 10 Fibonacci numbers\n");
  for (i=0;i<10;i++)
  {
    t = x + y;
    x = y;
    y = t;
    printf ("%d ",t); 
  }
  printf("\n");
  return (0);
}



Node.js
Node is kind of like Javascript without needing a browser. It's a nice, refreshing language.
You have to have Node locally installed and then run it in the terminal with 
node fibo.js.

fibo.js:

 x=0
 y=1
 console.log ("First 10 Fibonacci numbers.")
 for (i=0;i<10 font="" i="" nbsp="">
 {
     t = x + y
     x = y
     y = t
     console.log (t);
 } 



Javascript Load this one into a browser. Getting this to even show up in the browser was a pain. Had to remove all the html and script tags. Tag: means the tag inside of angle brackets. Close tag: means use the closing tag which is the tag proceeded with a forward slash.
Tag: html
Tag: body
Tag: script
 x=0
 y=1
 document.write("First 10 Fibonacci numbers.")
 for (i=0;i<10;i++) 
 {
     t = x + y
     x = y
     y = t
     document.write(t," ");
 } 

Close tag: script
Close tag: body
Close tag: html


Powershell
$x = 0
$y = 1

$enditer = 10

for ($i=0;$i -lt $enditer;$i++) 
{
  $t = $x + $y
  write-host $t " "
  $x = $y
  $y = $t
}

write-host "End of series"

Saturday, July 16, 2016

Redwood Park: Goats at Work

East Bay Regional Park is hiring cheap labor. Really cheap, but they do a job that few of us would want to do. Eat flammable underbrush. Lots of it. Enter the goats who will eat many things save for poison oak.




This is right beside the West Ridge Trail, near Moon Gate

They get to keep their horns. Hope they don't get hooked up on a tree.

Some sit down on the job.

Facial hair is ok.

But they're very clear about not eating poison oak.




Sunday, April 17, 2016

Walking with a Cell Phone is a bit Silly

People who walk while talking on their cell phones make me laugh.     Often.


Wednesday, March 23, 2016

No Joy in the Writing Contest

Of course, I didn't get any placement in the previous writing contest and I will get used to it, but there is a free humor poetry writing contest called the Wergle Flomp Humor Poetry Contest so I entered Poetry Smokes because there wasn't a publishing restriction on the entry.


You can enter the contest here:
Deadline is April 1st, 2016 and winning entries announced Aug 15, 2016, so breath holding is not advised.

AND there another fiction and "very short" (300-3000 words) fiction contest put on by Glimmer Train. Here is the entry form: https://glimmertrainpressinc.submittable.com/submit
I guess I'll let "The Road, The Tree, and The Human" have a go at the very short one. there is a $21 or $16 "reading fee" for these contests. (The poetry one is free).

https://winningwriters.com/our-contests/wergle-flomp-humor-poetry-contest-free/wergle-flomp-humor-poetry-contest-confirmation
The publishing restriction is that it can't have appeared in a print form, so online is ok.