Программа JAVA, чтобы найти самый большой премьер-фактор, но вывод неправильный? - PullRequest
1 голос
/ 19 июня 2019

Я возвращаю код (на Java) на Найти наибольший простой множитель из данного числа .

Я обнаружил, проверил все факторы, а затем проверил, простое это или нет .... Если это так, выведите наибольшее простое число.

import java.util.Scanner;

public class Problem3 {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number");
        int n = Integer.parseInt(sc.next()); // Takes input from the user.
        int p=0,i,j,max=0,c=0;

        for(i=1;i<n;i++) {
            if(n%i != 0) { //Checks for factors and assigns that value to "c"
                c = i;
                for(j=1;j<c;j++) {
                    if(c%j==0) { //checks for prime number or not, if so... assign that value to "p"
                        p = j;
                    }

                    if(max<p) { // Checks for largest Prime factors, and assigns that value to "max"
                        max = p;
                    }
                }
            }

        }

        System.out.println(max); // prints the maximum prime-factor value.
        sc.close();
    }

}

Я ожидаю, что выход 14 будет 7, но фактический выход 1

Ответы [ 3 ]

2 голосов
/ 19 июня 2019

Кажется, в вашем цикле for произошла ошибка.Я создал метод для этого с использованием Java 8. Попробуйте код ниже,

Java 8

public static void main(String[] args) {
    try (Scanner sc = new Scanner(System.in);) {
        System.out.println("Enter the number");
        int n = Integer.parseInt(sc.next()); // Takes input from the user.

        int max = IntStream.range(0, n).filter(q -> isFactor(n, q)).filter(q -> isPrimeNumber(q)).max().getAsInt();

        System.out.println(max); // prints the maximum prime-factor value.
    } catch (Exception e) {
        // TODO: handle exception
    }

}

public static boolean isPrimeNumber(int n) {
    int i, m = 0, flag = 0;
    m = n / 2;
    if (n == 0 || n == 1) {
        return false;
    } else {
        for (i = 2; i <= m; i++) {
            if (n % i == 0) {
                flag = 1;
                return false;
            }
        }
        if (flag == 0) {
            return true;
        }
    }
    return false;
}

public static boolean isFactor(int n1, int n2) {
    if(n2==0) {
        return false;
    }
    return n1 % n2 == 0;
}

Java 7

public static void main(String[] args) {
    try (Scanner sc = new Scanner(System.in);) {
        System.out.println("Enter the number");
        int n = Integer.parseInt(sc.next()); // Takes input from the user.

        int max = 0;

        for (int i = 0; i < n; i++) {
            if (isFactor(n, i)) { // checks for factor
                if (isPrimeNumber(i)) { // checks for prime
                    if (i >= max) { // checks for max number
                        max = i;
                    }
                }
            }
        }

        System.out.println(max); // prints the maximum prime-factor value.
    } catch (Exception e) {
        // TODO: handle exception
    }

}
1 голос
/ 19 июня 2019

Первичная проверка неверна. c является простым, только если c % j != 0 для всех 1

int max=0,c=0;

for(int i=1;i<n;i++) {
    if(n%i == 0) { //Checks for factors and assigns that value to "c"
        c = i;
        for(int j=2;j<c;j++) {
            if(c%j==0) { // not prime
                c = 0;
                break;
            }
        }
        if(max < c) { // if c > max, it must be > 0, which means it must be prime
            max = c;
        }
    }
}

System.out.println(max); // prints the maximum prime-factor value.
0 голосов
/ 19 июня 2019

Попробуйте этот код

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number");
    int n = Integer.parseInt(sc.next()); // Takes input from the user.
    int p = 0, i, j, max = 0, c = 0;

    for (i = 1; i < n; i++) {
        if (n % i == 0) { //Checks for factors and assigns that value to "c"
            c = i;
            if (isPrime(c) && c > max) {
                max = c;
            }
        }
    }

    System.out.println(max); // prints the maximum prime-factor value.
    sc.close();
}

private static boolean isPrime(int num) {
    if (num == 0 || num == 1) {
        return false;
    }
    for (int i = 2; i < num / 2; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...