Robert X.

asked • 07/22/21

JavaScript Question

How do I put the output on the second line?

Intended output(example)

Enter·the·number·up·to·which·you·would·like·to·look·for·perfect·numbers:

500↵

Looking·for·perfect·numbers·from·1·to·500↵

6·is·a·perfect·number·it's·factors·are:·1·2·3·↵ 28·is·a·perfect·number·it's·factors·are:·1·2·4·7·14·↵ 496·is·a·perfect·number·it's·factors·are:·1·2·4·8·16·31·62·124·248·↵

What I have:

Enter·the·number·up·to·which·you·would·like·to·look·for·perfect·numbers:

500↵

Looking·for·perfect·numbers·from·1·to·↵

6·is·a·perfect·number·it's·factors·are:·1·2·3·↵ 28·is·a·perfect·number·it's·factors·are:·1·2·4·7·14·↵ 496·is·a·perfect·number·it's·factors·are:·1·2·4·8·16·31·62·124·248·↵


My code:

import java.util.Scanner;




class PerfectNumbers {


public static boolean isPerfect(int N)


{


int sum = 0,j=0;


//sum the factors of the number N if they are equal , then it's perfect number


for (int i = 1; i < N - 1; i++)


{


if (N%i == 0)


{


sum += i;


}


}


if (N == sum)


return true;


else


return false;


}




public static String factors(int N)


{


String s="";


int first=1;


for(int i =1; i< N; i++)


{


if(N%i == 0)


{


if(first == 1)


{


//System.out.println("s"+s);


s = Integer.toString(i);


first=0;


}


else


{


s+=" ";


s+=Integer.toString(i);


//System.out.println("s"+s);


}


}


}


//System.out.println("s"+s);


return s;


}




public static void main(String[] args) {


Scanner sc=new Scanner(System.in);

System.out.print("Enter the number up to which you would like to look for perfect numbers:");

System.out.println("Looking for perfect numbers from 1 to ");

int n=sc.nextInt();


String []str=new String[20];

for(int i = 1 ; i < n;i++)


{



if(isPerfect(i))


{


System.out.println(""+i+" is a perfect number it's factors are: "+factors(i)+" " );


//System.out.println("It's factors are: "+factors(i));




}




}


}


}

1 Expert Answer

By:

Patrick B. answered • 07/22/21

Tutor
4.7 (31)

Math and computer tutor/teacher

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.