FIND A PERFECT NUMBER

Perfect Numbers
Submissions: 20008   Accuracy: 
36.64%
   Difficulty: Easy   Marks: 2
Associated Course(s):   Interview Preparation
    

Given a number N, check if a number is perfect or not. A number is said to be perfect if sum of all its factors excluding the number itself is equal to the number.
Input:
First line consists of T test cases. Then T test cases follow .Each test case consists of a number N.
Output:
For each testcase, in a new line, output in a single line 1 if a number is a perfect number else print 0.
Constraints:
1 <= T <= 300
1 <= N <= 1018
Example:
Input:
2
6
21
Output:
1
0

** For More Input/Output Examples Use 'Expected Output' option **


import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
public static void main (String[] args) {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
for(int i=0;i<t;i++)
{
    int n=s.nextInt();
    if(isperfect(n))
    {
        System.out.println("1");
    }
    else
    System.out.println("0");
}
}
static boolean isperfect(int n)
{
    // To store sum of divisors 
     int sum = 1; 
   
    // Find all divisors and add them 
    for ( int i=2; i*i<=n; i++) 
    { 
        if (n%i==0) 
        { 
            if(i*i!=n) 
                sum = sum + i + n/i; 
            else
                sum=sum+i; 
        } 
    }  
     // If sum of divisors is equal to 
     // n, then n is a perfect number 
     if (sum == n && n != 1) 
          return true; 
   
     return false; 
 
}
}



Author: Ayush Saluja

Comments

Popular posts from this blog

Problem Statement Of Real Estate Use Cases

Problem Statement Of Bank Marketing analysis

Hadoop