Home > Software design >  How to print greatest factor of number (using loop)
How to print greatest factor of number (using loop)

Time:09-05

Currently, I've been taking the Java Basic course on Programiz. There is a 'challenge' I have to solve to move forward, but I got stuck. Can anyone help me with this task?

Problem Description
Create a program to print the greatest factor of a number besides itself using a loop. Get an integer input and assign it to the number variable. Create a for loop that runs from i = number - 1 to i = 1. Inside the loop, check if number is perfectly divisible by i and break the loop.

This is the pre-built draft:

// Replace ___ with your code
import java.util.Scanner;

class Main {
    public static void main(String[] args) {

        // get input value for number
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();

        // run the loop from i = number - 1 to 1
        for (___) {

            // check if number is divisible by i
            // if true, print the value of i and break the loop
            if (number % i == 0) {
                ___
            }
        }

        input.close();
    }
}

This is how I try to do this:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {

        // get input value for number
        Scanner input = new Scanner(System.in);
        int number = input.nextInt();
        int largest = 0;

        // run the loop from i = number - 1 to 1
        for (int i = (n-1); i>=1; i--) {

            // check if number is divisible by i
            // if true, print the value of i and break the loop
            if (number % i == 0) {
                System.out.println(i);
                break;
            }
            else {
                System.out.println(i);//this is where I'm stuck
            }
        }

        input.close();
    }
}

Any ideas? I googled a lot, but couldn't find the answer.

CodePudding user response:

for future questions please add the issue too. change the for loop form

for (int i <= (n -1); i=1; i--) {

to

for (int i = (n -1); i >= 1; i--) {

CodePudding user response:

this is the correct way: import java.util.Scanner;

class Main { public static void main(String[] args) {

    // get input value for number
    Scanner input = new Scanner(System.in);
    int number = input.nextInt();
  

    // run the loop from i = number - 1 to 1
    for (int i = (number -1); i>=1; i--) {

        // check if number is divisible by i
        // if true, print the value of i and break the loop
        if (number % i == 0) {
            System.out.println(i);
            break;
        }
        
    }

    input.close();
}

}

  • Related