Fun With Numbers

Ken Jennings posses four questions about 2009 which I thought would be fun to answer by making a small JavaScript to calculate the answers:

From ken-jennings.com:

It turns out that 2009 is not a prime number, as I briefly wondered if it might be. In fact, one of its several divisors is a perfect square. What is that factor?

While you’re killing time on meaningless stuff (I imagine Friday is going to be a slow work day, if you’re in the office at all): what was the last year that had such a large perfect square as a factor? What will be the next one?

And what year is the next prime number?

Solution and code after the break.

  • Perfect square divisor found. 2009 is divisible by: 7^2 (49)
  • 2011 is a prime!
  • Perfect square divisor found. 2000 is divisible by: 10^2 (100)
  • Perfect square divisor found. 2016 is divisible by: 12^2 (144)

And the code:

<script type="text/javascript">

var i = 7; //divides by 1 and ?

var isNotPrimeFlag = false;
var isPrimeFlag = false;
var isSquareFlag = false;


function primeSearch(number){
//document.write("For the year " + number + "<br />");
	//Prime search
	while(i < number){

			if( number%i == 0){
				//document.write("<br />" + "Not a prime. " + number + " is divisible by: " + i);
				isNotPrimeFlag = true;
				break;
			}
			
		i++;
			if(i == number){
			document.write("<br />" + number + " is a prime!");
			isPrimeFlag = true;
			}
	}

}
function squareSearch(number){

	i = 7;
	
	//divisors is a perfect square search
	while((i*i) < number){

			if( number%(i*i) == 0){
				
				document.write("<br /> Perfect square divisor found. " +number + " is divisible by: " + i + "^2 (" + (i*i) + ")");
				isSquareFlag = true;
				break;
			}
			
		i++;	

	}
}

squareSearch(2009);

isSquareFlag = false;

for (j=2010;j<2100;j++){
	if(!(isPrimeFlag)){
		primeSearch(j);
	}
}

for (j=2008;j>1900;j--){

	if(!isSquareFlag){
		squareSearch(j);
	}
	
	if(isSquareFlag){
		break;
	}
}

isSquareFlag = false;
for (j=2010;j<2100;j++){

	if(!isSquareFlag){
		squareSearch(j);
	}
	
	if(isSquareFlag){
		break;
	}
}


</script>

Leave a Reply

Your email address will not be published. Required fields are marked *