※上海交通大学 整除问题(java)(难题,质因子分解)

题目描述
给定n,a求最大的k,使n!可以被a^k整除但不能被a^(k+1)整除。
输入描述:
两个整数n(2<=n<=1000),a(2<=a<=1000)
输出描述:
一个整数.
示例1
输入
复制
6 10
输出
复制
1

在这里插入图片描述

import java.util.*;
import java.io.*;
import java.text.* ;
public class Main
{
	static boolean[] notPrime = new boolean[1000];
    public static void main(String[] args){
    	try {
	        BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
	        String[] parts = br.readLine().split(" ");
	        int n = Integer.parseInt(parts[0]);
	        int a = Integer.parseInt(parts[1]);
	        System.out.println(getRes(n, a));
 	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
    public static void isPrime() {
    	notPrime[0] = notPrime[1] = true;
    	for(int i = 2; i < 1000; ++i) {
    		if(!notPrime[i]) {
    			for(int j = 2*i; j < 1000; j += i)
    				notPrime[j] = true;
    		}
    	}
    }
    public static int getRes(int n, int a) {
    	int[] count1 = new int[100];
    	int[] count2 = new int[100];
    	
    	int len = 0;
    	//质因子分解
    	for(int i = 2; i < 1000 && a!= 1; ++i) {
    		if(!notPrime[i]) {
    			if(a%i==0) {
    				count1[len] = i;
    				while(a>1 && a%i == 0) {
    					count2[len]++;
    					a = a/i;
    				}
    				len++;
    			}
    		}
    	}
    	int k = Integer.MAX_VALUE;
    	for(int i = 0; i < len; i++) {
    		int p = count1[i];
    		int num = 0;
    		//每一个p的倍数都将对n!贡献至少一个p因子
    		while(p <= n) {
    			num += n/p;
    			p = p * count1[i];//p再每多乘一个p因子,将会多贡献一个p因子
    		}
    		num = num/count2[i];//将a和n!比对
    		if(k > num) k = num;//找到共同最大的k
    	}
    	return k;
    }
    
}

发布了231 篇原创文章 · 获赞 22 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104206375