Construction and interpretation of SICP computer program 1.21 searching for factor Scheme, C + + implementation

Source: Internet
Author: User

Looking for prime factors

Requires the Smallest-divisor process in the book to find the minimum factor of 199, 1999, 19999.

Scheme Code:

Main process:

Define the process of finding prime numbers

, greater than the test value, then it must be a prime number

can and Divisible, then not prime, the minimum factor is 2

If not, go back to the process Find-div, and then try to divide it with 2+1, loop

#lang Racket (define (square x) (*x x)); Definition filter (define (smallest-Div N) (Find-div N2)) (Define (Find-Div N TD) (Cond (>( Square TD) N) N) ((DIVD?TD N) TD) (Else(Find-div N (+ TD1)))) (define (DIVD?a B) (= (remainder b a)0) );p the Rimer process, which equals true if the condition is met, otherwise false, denoted by #t and #f, similar to bool (Define (Primer?N) (= N (smallest-div N)))

Test:

In:

(Primer? 3)

(Smallest-div 199)

(Smallest-div 1999)

(Smallest-div 19999)

Out:

#t

199

1999

7

C + + Code:

intSquareintx) {    intsum = x*x; returnsum;}intFind_div (intNintTD) {    if(Square (TD) >N) {returnN; }    Elseif(! (n%TD)) {       returnTD; }    Else{find_div (n, TD+1); }}int_tmain (intARGC, _tchar*argv[]) {    intA, b,real; CIN>> a >>b; Real=Find_div (A, b); cout<< Real <<Endl; return0;}

Construction and interpretation of SICP computer program 1.21 searching for factor Scheme, C + + implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.