w3resource

Java Method Exercises: Display the factors of 3 in a given integer

Java Method: Exercise-21 with Solution

Write a Java method to display the factors of 3 in a given integer.

Pictorial Presentation:

Java Method Exercises: Display the factors of 3 in a given integer

Sample data:
(8) -> 8 = 8
(45) -> 45 = 3 * 3 * 5
(81) -> 81 = 3 * 3 * 3 * 3 * 1

Sample Solution:

Java Code:

import java.util.Scanner;
public class Main { 
 public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input an integer(positive/negative):");
        int n = in.nextInt();
        System.out.print("\nFactors of 3 of the said integer:\n");
        test(n);
        }

public static void test(int n){
    System.out.print(n + " = ");
    int result = n;
    while (result % 3 == 0){
        System.out.print("3 * ");
        result = result / 3;
    }
    System.out.print(result);
}
}

Sample Output:

Input an integer(positive/negative): 81

Factors of 3 of the said integer:
81 = 3 * 3 * 3 * 3 * 1

Flowchart :

Flowchart: Display the factors of 3 in a given integer

Java Code Editor:

Contribute your code and comments through Disqus.

Previous Java Exercise: Extract the first digit from an integer.
Next Java Exercise: Check whether every digit of a given integer is even.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Java: Tips of the Day

similarity:

Returns an array of elements that appear in both arrays.
Use Arrays.stream().filter() to remove values that are not part of second, determined using Arrays.stream().anyMatch().

public static <T> T[] similarity(T[] first, T[] second) {
    return Arrays.stream(first)
            .filter(a -> Arrays.stream(second).anyMatch(b -> Objects.equals(a, b)))
            // Make a new array of first's runtime type, but empty content:
            .toArray(i -> (T[]) Arrays.copyOf(new Object[0], i, first.getClass()));
}

Ref: https://bit.ly/3CJ7huF