Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

[] Asal sayıları bulma

//Asal Sayıları Bulmaya Yarayan Bir Program(Yazana teşekkürler) program Primes; { function IsPrime This function determines if a number is prime or not Parameters: x - the integer number to determine if prime or not Return value (Boolean): True if x is prime, else False Preconditions/Postconditions: None } function IsPrime( x: integer ) : Boolean; var factor : integer; begin if x < 2 then { No numbers < 2 are prime } IsPrime := False else if (x = 2) or (x = 3) then { 2 and 3 are prime } IsPrime := True else if not odd(x) then { other than 2, no even number is prime } IsPrime := False else begin { case: odd numbers > 3 } { look for an odd factor of x: if x has a factor, it must be less than sqrt(x) } factor := 3; while (sqr(factor) <= x) and ( x mod factor <> 0 ) do factor := factor + 2; { try next odd number } { loop will stop whether x is prime or not (THIS is GOOD!) afterward, must determine if it found a factor of x } IsPrime := x mod factor <> 0; end end; { procedure FindNextPrime This procedure finds the next prime starting from an initial guess Parameters: InitialGuess - first guess for next prime NextPrime - var parameter to store next prime in Precondition: InitialGuess is odd Postconditions: NextPrime holds the value of the next prime (and is odd) } procedure FindNextPrime( InitialGuess : integer; var NextPrime : integer ); var Guess : integer; begin Guess := InitialGuess; while not IsPrime( Guess ) do Guess := Guess + 2; NextPrime := Guess end; { procedure FindPrimes This procedure finds a series of prime numbers Parameters: NumOfPrimesToFind - the number of primes to find Preconditions: NumOfPrimesToFind is > 1 Postconditons: None } procedure FindPrimes( NumOfPrimesToFind : integer ); var Guess : integer; PrimeNum : integer; procedure PrintHeading; { nested procedure } begin writeln; writeln(' Primes'); writeln('----------------') end; begin PrintHeading; writeln(1:5,' ', 2:7); { first prime (2) is a special case } Guess := 3; { start with a odd number } for PrimeNum := 2 to NumOfPrimesToFind do begin FindNextPrime( Guess, Guess ); writeln(PrimeNum:5, ' ', Guess:7); Guess := Guess + 2 { next odd number } end end; { procedure GetInput This procedure gets the number of primes to find from user Parameters: NumOfPrimesToFind - var parameter to store number in Preconditions: None Postcondtions: NumOfPrimesToFind > 1 } procedure GetInput( var NumOfPrimesToFind : integer ); begin repeat write('How many primes do you wish to find? '); readln( NumOfPrimesToFind ); if NumOfPrimesToFind < 1 then writeln('Must find at least 1 prime!') until NumOfPrimesToFind >= 1; end; procedure PrintHeading; begin writeln(' Prime Finding Program'); writeln; writeln(' This program finds prime numbers'); writeln end; { main program } var NumOfPrimesToFind : integer; begin PrintHeading; GetInput( NumOfPrimesToFind ); FindPrimes( NumOfPrimesToFind ) end.