Download presentation
Presentation is loading. Please wait.
1
Hints for homework 6.2
2
divisors A divisor of an integer n, also called a factor of n, is an integer which evenly divides n without leaving a remainder. – It is important to note that 1 is a proper divisor of every natural number (except itself)
3
In C++, there are two arithmetic operators for integer operands you want to recall. – / c=a/b, a is the dividend, b the divisor, and c the quotient. – % c=a%b, c is the remainder.
4
Proper divisors The proper divisors do not include the number itself. – 10 is called a divisor of itself, but not a proper divisor.
5
Which numbers are the divisors of 12? Do the problem yourself first!
6
answer 1, 2, 3, 4, 6, 12.
7
Which numbers are the proper divisors of 12? Do the problem yourself first!
8
answer 1, 2, 3, 4, 6
9
In this homework we care about all proper divisors We care about the sum of all proper divisors of a given number.
10
What is the sum of all the proper divisors of 12? Do the problem yourself first!
11
answer 16
12
How to write a function to get the result?
13
The Simplest way A brute-force algorithm to find the divisors of a natural number n is to enumerate all integers from 1 to n, and check whether each of them divides n without remainder. To test every number smaller than the target number, to see whether it can be evenly divided by the target number, – If yes, you accumulate it to sum, if not do nothing – Test next one – Until you reach the upper bound
14
You should be able to implement it! Using a separate function, And the function mainly consists of a loop
15
You can stop here, but … For those who would like to improve their understanding, you might want to think of other better solutions! Do you have a better solution?
16
A unique observation Observation is that, you get a divisor at the same time you get the complement divisor too. – For example, the time for you to discover 2 is a proper divisor for 8, you automatically discover 4 too.
17
A more efficient solution! Square root version. – You do not need to test all the numbers between 1 and a given number to find out all the divisors. You can early terminate the process using the square root as the upper bound – if you really get the idea, make sure test it on different numbers such as 100 and 99, 98 etc. to see whether any divisors (especially the square root itself) are missed or counted twice. A little bit tricky! – If you have questions about square root version. You can always use the simplest method you can get.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.