素数判定法

by atsumo
♥0 | Line 76 | Modified 2009-12-05 19:36:21 | MIT License
play

ActionScript3 source code

/**
 * Copyright atsumo ( http://wonderfl.net/user/atsumo )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/zfEf
 */

package {
	
	import com.bit101.components.PushButton;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.text.TextField;
	
	public class wonderfl extends Sprite {
		
		private var _tf:TextField;
		private var _count:int;
		private var _isPrime:Boolean;
		
		
		public function wonderfl()
		{
			
			initialize();
			
		}
		
		private function initialize():void
		{
			_tf = new TextField();
			_tf.width = stage.stageWidth;
			_tf.height = stage.stageHeight;
			_tf.wordWrap = true;
			_tf.y = 50;
			addChild(_tf);
			
			new PushButton(this, 0,0,"start",handleStartClick);
			new PushButton(this, 120,0,"stop",handleStopClick);
			new PushButton(this, 240,0,"rest",handleResetCountClick);
			new PushButton(this, 360,0,"clean",handleTextClean);
		}
		
		private function handleStartClick(e:Event):void
		{
			if(hasEventListener(Event.ENTER_FRAME))
				removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
			
			addEventListener(Event.ENTER_FRAME, handleEnterFrame);
		}
		
		private function handleStopClick(e:Event):void
		{
			if(hasEventListener(Event.ENTER_FRAME))
				removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
		}
		
		private function handleResetCountClick(e:Event):void
		{
			_count = 0;
		}
		
		private function handleTextClean(e:Event):void
		{
			_tf.text = "";
		}
		
		private function handleEnterFrame(e:Event):void
		{
			if(isPrime(_count))
				addText(String(_count));
			
			_count++;
			
		}
		
		private function addText(str:String):void
		{
			if(_tf == null)
				return;
			
			if(_tf.length != 0)
				str = "," + str;
			
			_tf.appendText(str);
		}
		
		
		
		private function isPrime(i:int):Boolean
		{   
			
			if( i < 2 )
				return true;
				
			else if( i == 2)
				return true;
			
			if( i % 2 == 0)
				return false;
			
			for(var n:int = 3; n*n <= i; n+=2)
			{
				if( i % n == 0 )
					return false;
			}
			
			return true;
		}
		
		
	}
}