0

I was solving Prime factor for a given number , when I tried a program using long data type as the parameter to a method and calling it in the main method after assigning the value to the parameter in main method it gives me error , but when I tried the same program using scanner for taking input from the console for the passing the long data type as parameter it displays result.why is this so ? in both the cases I am using the same number; Assigning the vale to the parameter in the main method it self it show error Main.java:42: error: integer number too large: 600851475143 long n =600851475143 ;

import java.util.*;
import java.lang.*;
import java.io.*;
class primeFactors
{
        public static void primeFactors(long n) 
    { 
        while (n%2==0) 
        { 
            System.out.print(2 + " "); 
            n /= 2; 
        } 

        for (int i = 3; i <= Math.sqrt(n); i+= 2) 
        { 
            
        while(n%i == 0) 
            { 
                System.out.print(i + " "); 
                n /= i; 
            } 
        } 
        if (n > 2) 
            System.out.print(n); 
    } 

    public static void main (String[] args) 
    { 
        long n =600851475143 ; 
        primeFactors(n); 
    } 
}

using scanner Class for passing the input to the method. scanner input is 600851475143.

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

class primefactors
{
        public static void primeFactors(long n) 
    { 
        while (n%2==0) 
        { 
            System.out.print(2 + " "); 
            n /= 2; 
        } 

        for (int i = 3; i <= Math.sqrt(n); i+= 2) 
        { 
            
        while(n%i == 0) 
            { 
                System.out.print(i + " "); 
                n /= i; 
            } 
        } 

        if (n > 2) 
            System.out.print(n); 
    } 

    public static void main (String[] args) 
    { 
        long n;
        Scanner s1=new Scanner(System.in);
        n=s1.nextLong();
        primeFactors(n); 
    } 
}
shilpi
  • 27
  • 5

1 Answers1

1

You need to an L at the end of a long! I copied an pasted your code with the L at the end and it worked!

honk
  • 9,137
  • 11
  • 75
  • 83
samarmohan
  • 350
  • 3
  • 12