Computer Science, asked by PuruVyas, 6 months ago

Write a java program to find out the sum of factors of number using for loop.

p.s: don't write anything if you don't have the answer please this will be really helpful of I only get the answer (not from google)

I ONLY WANT ANSWER IF YOU DON'T UNDERSTAND IT DON'T WRITE​

Answers

Answered by anindyaadhikari13
29

Question:-

Write a Java program to find the sum of factors of a number using for loop.

Solution:-

Here is your program written in Java.

import java.util.*;

class Sum

{

public static void main(String args[])

{

int n, s=0, i;

Scanner sc=new Scanner(System.in);

System.out.print("Enter a number: ");

int n=sc.nextInt();

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

{

if(n%i==0)

s+=i;

}

System.out.println("Sum of factors is: "+s);

// @AnindyaAdhikari

}

}

Answered by ankhidassarma9
2

import java.io.*;

import java.util.*;

public class Main {

    // Function to calculate sum of all factors of a given number

   static int divSum(int n)

   {

        if(n == 1)

          return 1;

       // Final result of summatio of factors

       int result = 0;

            //  all divisors which divides 'num'

       for (int i = 2; i <= Math.sqrt(n); i++)

       {

           // checking if 'i' is divisor of 'n'

           if (n % i == 0)

           {

               // if both divisors are same

               // then add that once else add

               // both

               if (i == (n / i))

                   result += i;

               else

                   result += (i + n / i);

           }

       }

   

       // Add 1 and n to result as above loop

       // considers proper divisors greater

       // than 1.

       return (result + n + 1);

       

   }

   

  public static void main(String[] args)

   {

       Scanner sc= new Scanner(System.in);

        System.out.println("Enter a number");

       int n= sc.nextInt();

       System.out.println(divSum(n));

   }

}

Similar questions