<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Computer Science &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/category/computer-science/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Tue, 05 Oct 2021 05:10:05 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to calculate median from an array in Java</title>
		<link>https://codepills.com/how-to-calculate-median-from-an-array-in-java/</link>
					<comments>https://codepills.com/how-to-calculate-median-from-an-array-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 01 Oct 2021 10:13:54 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[bubble sort]]></category>
		<category><![CDATA[mean]]></category>
		<category><![CDATA[median]]></category>
		<category><![CDATA[quicksort]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1251</guid>

					<description><![CDATA[In this short article, we will see how to compute median in Java. <a href="https://codepills.com/how-to-calculate-median-from-an-array-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>In this short article, we will see how to compute median in Java.</p>
<p><span id="more-1251"></span></p>
<ul>
<li><a href="#what_is_median">What is median?</a></li>
<li><a href="#difference_between_median_and_mean">What is the difference between the median and mean?</a></li>
<li><a href="#algorithm">Calculate median with simple algorithm</a></li>
<li><a href="#conclusion">Conclusion</a></li>
</ul>
<h2 id="what_is_median">What is median?</h2>
<p>First of all, let&#8217;s get a good idea what <strong>median</strong> actually is. Let&#8217;s look at wiki definition:</p>
<blockquote><p>The median of a list of numbers can be found by first sorting the numbers ascending. If there is an odd number of values, the middle one is picked. If there is an even number of values, the median is then defined to be the average of the two middle values. (Wikipedia)</p></blockquote>
<p>So when we take the definition of median, we need to find the middle in the sorted array.</p>
<h2 id="difference_between_median_and_mean">What is the difference between the median and mean?</h2>
<p>The essential difference is that <strong>the mean</strong> gives a rough average (sum all elements together and divide the sum by the number of elements in the collection) of the whole dataset. At the same time, <stron>the median</stron> will provide the exact centric value, which falls between the smallest and highest value.</p>
<p>It is important to note that a single centric value can be picked only from ordered values arranged in an ascending or descending order for the median.</p>
<p>For example, if I have an array <code>[1,2,3,4,5]</code>, number 3 is the median. But if have an arrray <code>[1,2,3,4,5,6]</code>, number 3.5 is the median.</p>
<h2 id="algorithm">Calculate median with simple algorithm</h2>
<p>Let&#8217;s use few words to describe our algorithm for computing <strong>the median</strong>.</p>
<p>First, we will need to take input. The inputs are the <code>int</code> numbers in the array and the size of the collection. One crucial thing to remember is to <strong>always keep in mind that the values in an array need to be sorted for computing median</strong> Order, ascending or descending, is necessary because we are looking for the value in the centre of the array.</p>
<p>Sorting array happens before computing median, and it is not part of the algorithm for computing median. Therefore, you can use any known sorting algorithm such as quicksort, bubble sort etc.</p>
<p>After taking the inputs, we must first check whether <strong>the number of elements in the array is odd or even</strong>.</p>
<p><u>If the number of elements in the array is even</u>, we compute the median by taking two central pieces and divide them by two.</p>
<p>As we are familiar with arrays in computer science, array order starts with zero and ends with the number of elements minus one. Therefore, when an array length is an even number, we must select the middle array element and element before it.</p>
<p>Eventually, for computing the median for even array length, a division with a number represented as a double value will secure that median with decimal points. Otherwise, division with the number represented as int will floor the number, and the median will be incorrect.</p>
<p>Otherwise, <u>if the number of elements in the array is odd</u>, we compute the median by taking the centric array element.</p>
<p>But, again, as we are familiar with arrays in computer science, array order starts with zero and ends with the number of elements minus one.</p>
<p>We will do a small trick, which can look unnatural at first sight. We add one to the number of array elements in the array of odd length, then divide it by two. And then, we subtract from division one. The resulting number will give us the index position of the central component of the array of odd lengths.</p>
<pre><code class="language-java">public class Median {
    public static void main(String arg[]) {
        int oddLength = 5;
        int oddArr[] = new int[oddLength];
        oddArr[0] = 10;
        oddArr[1] = 30;
        oddArr[2] = 50;
        oddArr[3] = 70;
        oddArr[4] = 90;

        System.out.println("Median for odd length array is : " + computeMedian(oddArr, oddLength);
    
        int evenLength = 6;
        int evenArr[] = new int[evenLength];
        evenArr[0] = 10;
        evenArr[1] = 30;
        evenArr[2] = 50;
        evenArr[3] = 70;
        evenArr[4] = 90;
        evenArr[5] = 100;
    
        System.out.println("Median for even length array is :" + computeMedian(evenArr, evenLength);
    }
    
    private static double computeMedian(int[] arr, int n) {
        if (n % 2 == 0) {
            return (arr[n/2 - 1] + arr[n/2]) / 2.0;
        } else  {
            return arr[(n+1)/2 - 1];
        }
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">Median for odd length array is : 50
Median for even length array is : 60</code></pre>
<h2 id="conclusion">Conclusion</h2>
<p>This article has shown us a simple algorithm for how to compute median in Java.</p>
<p>It is important to remember that we can compute the median only on sorted arrays. Ascending or descending order does not matter unless we are looking for the value in the centre of the array.</p>
<p>Sorting of the array can happen before computing the median, and you can use any known sorting algorithm.</p>
<p>Did you find computing median easy? Do you have your trick or know another way <u>how to calculate median in Java</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-calculate-median-from-an-array-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Project Euler Problem 3 &#8211; Largest prime factor</title>
		<link>https://codepills.com/project-euler-problem-3-largest-prime-factor/</link>
					<comments>https://codepills.com/project-euler-problem-3-largest-prime-factor/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 16 Jan 2016 13:10:18 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<guid isPermaLink="false">http://codekopf.com/?p=382</guid>

					<description><![CDATA[Project Euler Problem 3 is the first problem in which I realized that the brute-force computation is not the best way to achieving the results. Here is the problem description: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? <a href="https://codepills.com/project-euler-problem-3-largest-prime-factor/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Project Euler Problem 3 is the first problem in which I realized that the brute-force computation is not the best way to achieving the results. Here is the problem description:</p>
<blockquote><p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p></blockquote>
<p><span id="more-382"></span></p>
<p>The idea is to compute the biggest prime factor of the number 600851475143. Fortunately I did not understand idea very well and I start looking for the biggest prime number under the 600851475143 number. Here is the code for searching the biggest prime number smaller than 10000.</p>
<pre class="tab-convert:true lang:php decode:true">&lt;?php 
$endNumber = 10000; 
$primeArray = array(2);

for ($i=2;$i&lt;=$endNumber;$i++) {
        $isPrime = null; 
        $isNotPrime = null; 
        foreach ($primeArray as $prime) {
                switch ($i%$prime == 0) {
                        case true:
                                $isNotPrime = true; 
                                break;
                        case false:
                                $isPrime = true;
                                break;
                }
                if ($isPrime == true &amp;&amp; $isNotPrime == false) {
                        if ($prime === end($primeArray)) {
                                array_push($primeArray, $i);
                        }
                }
        }
}

foreach ($primeArray as $num) {
	echo $num."&lt;br&gt;";
};
?&gt;</pre>
<p>When I made this code I realized something is wrong. Server default response exceeded default 30s and server outputed error. Brute force is not definitely not the right way to search for the bug prime numbers.</p>
<p>Computing the big prime number (and anything around  the 600 billions number is a big number) takes enormous computational power. Does the Problem 3 really ask me to compute such difficult computations?</p>
<p>I check an online resources for the algorithms for computing  the big prime numbers. I found out that I did not understand the Problem 3 description correctly. Instead of looking for the biggest prime number under 600851475143 the idea is to actually find the biggest <span style="text-decoration: underline;">prime factor</span> of the number 600851475143 . This is the task from the Math lecture of an elementary school .</p>
<pre class="tab-convert:true tab-size:10 lang:php decode:true ">&lt;?php
define('NUMBER', 600851475143);
$whileEnd = NUMBER;
$number = NUMBER;
$division = 2;
$primeFactor = array();

while ($division &lt;= $whileEnd) {
	if (fmod($number, $division) == 0) {
		$number = $number/$division;
		array_push($primeFactor, $division);
		// echo $number." - ".$division.". &lt;br&gt;";
	} else {
		$division++;
	}
	$whileEnd = round(NUMBER/$division) + 1;
}

echo "The biggest prime is ".end($primeFactor)." and last round ended at ".$division." .";
?&gt;</pre>
<p>The idea is simple. Every number is possible to divide on a multiple of several prime numbers, for example the number 90 can be divide on the multiple of 2*3*3*5 where the number 5 is <span style="text-decoration: underline;">the biggest prime factor</span>. So let&#8217;s try to divide the original number starting from the number 2.</p>
<p>If the number 2  is the prime number, we divide a reminder further by the number 2. We repeat the divide till the reminder is not dividable by current number.</p>
<p>If the number is not dividable by the current number, we increase the division number by 1 and try the whole process  with the remainder again.</p>
<p>We do it until (current number division the original number) times . Anything bigger this can not be the prime number of the original number. Thus by increasing the division we decrease the threshold for the end of loop.</p>
<h2>Improvements for the Problem 3</h2>
<p>I believe this is the algorithm for which exist many improved versions doing the faster computation of the prime numbers. While reviewing the code the best way to speed up the loop would be cleverly get rid of the all multiple of the all previous prime numbers. Unfortunately we can not use a <a title="Fibonacci algorithm Project Euler Problem 3" href="http://codekopf.com/2016/01/16/project-euler-problem-2-fibonacci-sequence/" target="_blank">Fibonacci algorithm</a> from the previous Project Euler Problem 3.</p>
<h2>Hint</h2>
<p>While working on the algorithm I encountered big problem with modulo. Using a normal operator % with such big number leads to incorrect results caused by float. The PHP math function fmod provide correct result.</p>
<pre class="lang:php decode:true">&lt;?php
$number = 600851475143;
$division = 3;
echo $number%$division;        // result 0
echo fmod($number, $division); // result 2
?&gt;
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/project-euler-problem-3-largest-prime-factor/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Project Euler Problem 2 – Fibonacci sequence</title>
		<link>https://codepills.com/project-euler-problem-2-fibonacci-sequence/</link>
					<comments>https://codepills.com/project-euler-problem-2-fibonacci-sequence/#comments</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 16 Jan 2016 10:52:59 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<guid isPermaLink="false">http://codekopf.com/?p=379</guid>

					<description><![CDATA[Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, … Find the sum of all the even-valued terms in the sequence which do not exceed four million. <a href="https://codepills.com/project-euler-problem-2-fibonacci-sequence/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Solving the Project Euler Problem 2 is simple and I believe it still does not required great processing power to search for the clever algorithms. The description of Problem 2 is:</p>
<blockquote><p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:</p>
<p>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …</p>
<p>Find the sum of all the even-valued terms in the sequence which do not exceed four million.</p></blockquote>
<p><span id="more-379"></span></p>
<p>In the order to find a final sum, first it is necessary to generate the Fibonacci sequence. The sum of the first 2 elements in the sequence creates the third. The loop than go on and the second and the third element create forth , etc.</p>
<p>All we need to do now do is just to check if the newly generated number is dividable by 2. If it is we can sum it up with the rest. The sum is already 2 since we begin by generating the 3rd number (the sum of first 2 elements $a and $b).</p>
<p>So the algorithms goes like this:</p>
<ol>
<li>Definition of starting variables.</li>
<li>Loop for generating +1 bigger number.</li>
<li>Check if number is dividable by 2.</li>
<li>If yes, number is summed.</li>
<li>Output of result.</li>
</ol>
<h2>PHP:</h2>
<pre class="lang:php decode:true">&lt;?php 
$sum = 2;
$a = 1;
$b = 2;
$c = null;
while ($c &lt; 4000000) {
	$c = $a + $b;
	if($c%2 == 0) {
		$sum += $c;
	}
	$a = $b;
	$b = $c;
}
echo $sum;
?&gt;</pre>
<h2>Java:</h2>
<pre class="lang:java decode:true">public class Project_Euler_Problem_002 {
	public static void main(String[] args) {
		
		System.out.println("Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:");
		System.out.println("1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …");
		System.out.println("Find the sum of all the even-valued terms in the sequence which do not exceed four million.");

		int sum = 2, a = 1, b = 2, c = 0;
		while (c &lt; 4000000) {
			c = a + b;
			if(c%2 == 0) {
				sum += c;
			}
			a = b;
			b = c;
		}
		
		System.out.println("\n"+ "Sum is: " + sum);;
	}
}</pre>
<p>Hint:  While reviewing the algorithm with the solutions of others I notice a difference. This algorithm is based on the Fibonacci sequence starting 1,2,3&#8230; not 1,1,2,3.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/project-euler-problem-2-fibonacci-sequence/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Project Euler Problem 1 &#8211; Multiples of 3 and 5</title>
		<link>https://codepills.com/project-euler-problem-1-multiples-of-3-and-5/</link>
					<comments>https://codepills.com/project-euler-problem-1-multiples-of-3-and-5/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 16 Jan 2016 10:09:38 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[math]]></category>
		<guid isPermaLink="false">http://codekopf.com/?p=377</guid>

					<description><![CDATA[If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. <a href="https://codepills.com/project-euler-problem-1-multiples-of-3-and-5/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>I was randomly searching for best place to learn &#8220;programming by doing&#8221; and I have found link on <a href="https://projecteuler.net/" rel="nofollow">Project Euler</a>. I really like the idea of the project and I decided to join. Here is a description of the first Project Euler problem:<span id="more-377"></span></p>
<blockquote><p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</p></blockquote>
<p>The problem is very easy. We are checking division of the numbers 3 and/or 5, the end number is not high and an idea of the sum is very clear. Despite the fact we need to brute-forcefully iterate all over the first 1000 numbers, I did not think much about any other complicated algorithm. The brute-force can be enough in this case.</p>
<h2>PHP:</h2>
<pre class="lang:php decode:true ">&lt;?php 
$sum = 0;
for ($i=0;$i&lt;1000;$i++) {
	if(($i%3 == 0) OR ($i%5 == 0)){
		$sum += $i;
	}
}
echo $sum;
?&gt;
</pre>
<h2>JAVA:</h2>
<pre class="lang:java decode:true">public class Project_Euler_Problem_001 {

	public static void main(String[] args) {
		
		System.out.println("If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.");
		System.out.println("Find the sum of all the multiples of 3 or 5 below 1000.");

		int sum = 0;
		for (int i = 0; i&lt;1000; i++) {
			if((i%3 == 0) || (i%5 == 0)){
				sum += i;
			}
		}
		System.out.println("\n"+ "Sum is: " + sum);;
	}
}</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/project-euler-problem-1-multiples-of-3-and-5/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
