Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.Math;
- /* ==================================
- chapter 4: Loops
- Ex16: friendly numbers
- ==================================
- */
- public class MyProgram {
- /* function to get the sum of divisors */
- public static int getSum(int number){
- int maxD = (int)Math.sqrt(number); //loop's range is [2,√num]
- int sum=1; //every number can divide by 1
- int divisor; //represent divisors bigger than the search range
- for(int i = 2; i <= maxD; i++)
- {
- if(number % i == 0)
- {
- /*
- if i divide the number:
- - add i to sum
- - init divisor
- */
- sum += i;
- divisor = number/i; //must be one of the divisors because the number can divide by i
- if(divisor!=i) //if the divisor is bigger than the loop's range → add divisor to sum
- sum+=divisor;
- }
- }
- return sum;
- }
- public static void main(String[] args) {
- final int SIZE =10;
- int counter = 0;
- int num1,num2;
- for(num1=1;counter<SIZE;num1++){
- num2=getSum(num1);
- if( num2>num1 && (num1==getSum(num2) ) ) {
- //we found a match! they should get f*** married
- System.out.println(num1 + " and " + num2 + " are mates");
- counter++;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment