(C++/JAVA)分解质因数问题

荒凉一梦 提交于 2020-02-08 02:10:17

将一个合数分解质因数输出。

C++:

#include<iostream>
using namespace std;
bool ISSS(int p) {
	for (int q = 2; q <= sqrt(p); q++) {
		if (p % q == 0) {
			return false;
		}
	}
	return true;
}
void FJZYS(int a){
	if (ISSS(a) == true){
		cout << a << " ";
	}
	else{
		for (int i = 2; i <= sqrt(a); i++){
			if (a%i == 0){
				cout << i << " ";
				return FJZYS(a / i);
			}
		}
	}
}
int main(){
	int a;
	cin >> a;
	FJZYS(a);
}

JAVA:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dm;

import java.util.Scanner;

/**
 *
 * @author Lenovo
 */
public class DM {

    /**
     * @param args the command line arguments
     */
    public static boolean ISSS(int p) {
        for (int q = 2; q <= Math.sqrt(p); q++) {
            if (p % q == 0) {
                return false;
            }
        }
        return true;
    }

    public static int FJZYS(int a) {
        if (ISSS(a) == true) {
            System.out.print(a + " ");
            return 0;
        } else {
            for (int i = 2; i <= Math.sqrt(a); i++) {
                if (a % i == 0) {
                    System.out.print(i + " ");
                    FJZYS(a / i);
                    break;
                }
            }
            return 0;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int number = sc.nextInt();
        FJZYS(number);

    }
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!