Project Euler #241: Perfection Quotients

  • + 0 comments

    Can someone tell why this code isn't working for range<10^18?? I know the max range in java for long is 10^19, but at least it should give correct for those test cases.!

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        public static int perfect(long n){
            long sum=n+1;
            for(long i=2;i<=Math.sqrt(n);i++){
                if(n%i==0)
                sum+=i;
            }
            if(sum==n)
            return 1;
            else
            return 0;
        }
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            Scanner sc=new Scanner(System.in);
            long n=sc.nextLong();
            long sum=0;
            for(long i=1;i<=n;i++){
                if(perfect(i)==1){
                    long sigma=2*n;
                    double p=sigma/n;
                    long k=(long)p;
                    if(k-p==0.5)
                    sum+=i;
                }
            }
            System.out.println(sum);
        }
    }