zoukankan      html  css  js  c++  java
  • PAT 1096. Consecutive Factors

    Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 356*7, where 5, 6, and 7 are the three consecutive numbers. Now given any positive N, you are supposed to find the maximum number of consecutive factors, and list the smallest sequence of the consecutive factors.

    Input Specification:

    Each input file contains one test case, which gives the integer N (1<N<231).

    Output Specification:

    For each test case, print in the first line the maximum number of consecutive factors. Then in the second line, print the smallest sequence of the consecutive factors in the format "factor[1]factor[2]...*factor[k]", where the factors are listed in increasing order, and 1 is NOT included.

    Sample Input:

    630

    Sample Output:

    3
    567

    分析

    这道题自己的解法超时了,于是看了别人的解法,最后输出的长度是不会超过12的,因为13的阶乘大于2^31了,并且可以知道如果长度大于等于2的话,那么第一个数是一定小于sqrt(n)的,否则乘积一定大于n.
    附上别人的解析:
    用暴力破解,一个个地尝试呀~既然是递增连续的因子长度~那么肯定是不重复的几个连着的数字相乘咯~然后就想到了阶乘的概念对不对,首先题目说了n最大就2的31次方,后来我掐指一算就知道了2的31次方是介于12的阶乘和13的阶乘之间的大小的~也就是说~~所求连续因子的长度再怎么长,也长不过12个数字~那就从len=12开始,一直到len=1,看看能不能找到一个满足条件的序列咯~
    假如长度比1大~那么至少得两个相邻的数相乘~那么这两个数的乘积是不可能超过n的~【就是说如果不止一个因子相乘,那么所求因子序列的第一个数字不可能超过sqrt(n)】那就从start = 2开始(和从1开始相乘是一个意思啦= =乘不乘以1不都一样嘛= =)一直到start = sqrt(n),把start * (start+ 1)(start+2)…【嗯对一共要乘以len的长度个~因为我们现在在尝试是否有连续的len长度的因子相乘满足条件】,乘完了的结果ans看看是不是n的约数~【就是看看n%ans是不是等于0咯】,等于0就好办啦,说明已经找到这个最长的连续因子啦~快输出.然后直接return.耶耶耶.要是没找到,那说明什么呢。。说明它是个质数(就是说说明它因子只有他自己本身),那就输出长度为1,而且因子就是n本身咯
    你可能会想。。既然len=1为什么要算?因为题目里说输出最小的连续因子序列,那么如果这个数不是质数,也就是说在检验len=1的时候发现了一个比这个数小的因子x,那个这个x就是最小的因子啦,就不能够是等到最后一句输出n为最小的因子啦,如果n是质数,那么小于sqrt(n)的限定情况下会保证它不找到n的本身这个数的,所以到最后要加上printf(“1 %d”, n);哦,保证它是质数的时候也能被输出答案.

    #include<iostream>
    #include<math.h>
    using namespace std;
    int main(){
    	long long int n;
    	cin>>n;
    	long long int max=sqrt(n);
    	for(int len=12;len>=1;len--)
    	    for(int start=2;start<=max;start++){
    	    	long long int ans=1;
    	    	for(int i=start;i-start<=len-1;i++)
    	    		ans*=i;
    	    	if(n%ans==0){
    	    		printf("%d
    %d",len,start);
    	    		for(int i=start+1;i-start<=len-1;i++)
    	    		    printf("*%d",i);
    	    		return 0;
    			}
    		}
    	printf("1
    %d",n);
    	return 0;
    }
    
  • 相关阅读:
    Advanced Installer文件和文件夹页面中的临时文件操作
    celery使用方法
    网站高并发之道
    大话程序猿眼里的高并发
    StringTokenizer类的使用
    linux下查看最消耗CPU、内存的进程
    分享10条PHP性能优化的小技巧,帮助你更好的用PHP开发:
    json 除去转义字符以及查看json错误
    关于 redis、memcache、mongoDB 的对比
    QPS 与 TPS 简介
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/8420899.html
Copyright © 2011-2022 走看看