Advertisement
WallHero

TP02E03

Sep 22nd, 2020
855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Stack;
  3.  
  4. public class PuntoTres {
  5.  
  6.     Scanner scanner = new Scanner(System.in);
  7.     public static void main(String[] args) {
  8.         PuntoTres myApp = new PuntoTres();
  9.        
  10.         myApp.run();
  11.  
  12.     }
  13.    
  14.     Stack<Long> divisorsOfN(Long n)
  15.     {
  16.         Stack<Long> ret = new Stack<Long>();
  17.         for(long i = 1; i*i <= n; i++)
  18.         {
  19.             if(n%i == 0)
  20.             {
  21.                 ret.push(i);
  22.                 if(n/i != i) ret.push(n/i);
  23.             }
  24.         }
  25.         return ret;
  26.     }
  27.    
  28.     long forceReadLong()
  29.     {
  30.         long n = 0;
  31.         while(true)
  32.         {
  33.             try
  34.             {
  35.                 System.out.println("Introduzca el valor de N:");
  36.                 n = Long.parseLong(scanner.next());
  37.                 return n;
  38.             }
  39.             catch(Exception ex)
  40.             {
  41.                 System.out.println("Se introdujo un número inválido, reintente.");
  42.             }          
  43.         }
  44.     }
  45.    
  46.     boolean checkPerfectNumber(Long n, Stack<Long> divisors)
  47.     {
  48.         Long sumOfDivs = 0*1L;
  49.         while(!divisors.isEmpty()) sumOfDivs+=divisors.pop();
  50.         return sumOfDivs-n == n;
  51.     }
  52.    
  53.     void run()
  54.     {
  55.         Long n = forceReadLong();
  56.         Stack<Long> divisors = divisorsOfN(n);
  57.         System.out.println(checkPerfectNumber(n, divisors) ? "Es número perfecto." : "No es número perfecto.");
  58.     }
  59.  
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement