zoukankan      html  css  js  c++  java
  • PAT Advanced 1096 Consecutive Factors (20) [数学问题-因子分解 逻辑题]

    题目

    Among all the factors of a positive integer N, there may exist several consecutive numbers. For example, 630 can be factored as 3*5*6*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

    题目分析

    已知一个整数N,求所有N的连续因子因式分解中,最长连续因子个数和最小连续因子序列
    注:最小连续因子序列的长度其实就是最长连续因子个数(因为连续因子序列的第一个数越大,连续因子序列越短)

    解题思路

    1. 连续因子数
      1.1 若为0,表示N是质数,因子只有1和N本身
      1.2 若大于0
      1.2.1 若等于1,表示N因子分解后,一个因子<=sqr(n),一个因子>=(sqr(n))
      1.2.2 若大于1,表示N因子分解后,可以找到连续因子

    易错点

    1 注意连续因子数为0和连续因子数为1的不同情况区分
    2 最小连续因子序列的长度其实就是最长连续因子个数(因为连续因子序列的第一个数越大,连续因子序列越短)

    Code

    #include <iostream>
    #include <cmath>
    using namespace std;
    int main(int argc,char * argv[]) {
    	int n;
    	scanf("%d",&n);
    	int sqr=(int)sqrt(1.0*n);
    	int len = 0,first=0;
    	for(int i=2; i<=sqr; i++) {
    		int temp =1;
    		int j; 
    		for(j=i; j<=sqr; j++) {
    			temp*=j;
    			if(n%temp!=0)break;
    		}
    		if(j-i>len) {
    			len=j-i;
    			first = i;
    		}
    	}
    	if(len==0) printf("1
    %d", n);
    	else {
    		printf("%d
    ",len);
    		for(int i=first; i<first+len; i++) {
    			if(i!=first)printf("*");
    			printf("%d", i);
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    require的特点
    require和load的不同之处
    关于“load”方法
    puts方法要点
    用类解释对象的由来
    以方法调用的原理解释Ruby中“puts ‘Hello‘”
    Ruby中方法的设计理念
    Ruby中puts,print,p的区别
    Ubuntu16.04安装MongoDB的Ruby驱动
    使用spring框架,用xml方式进行bean装配出现“The fully qualified name of the bean's class, except if it serves...”
  • 原文地址:https://www.cnblogs.com/houzm/p/12268223.html
Copyright © 2011-2022 走看看