Maximum Multiple

Maximum Multiple

Problem Description

Given an integer n, Chiaki would like to find three positive integers x, y and z such that: n=x+y+z, x∣n, y∣n, z∣n and xyz is maximum.

Input

There are multiple test cases. The first line of input contains an integer T (1≤T≤106), indicating the number of test cases. For each test case:
The first line contains an integer n (1≤n≤106).

Output

For each test case, output an integer denoting the maximum xyz. If there no such integers, output −1 instead.

Sample Input

3
1
2
3

Sample Output

-1
-1
1

題目概述

最大的多個

問題描述

給定一個整數n,Chiaki想找到三個正整數x,y,z,這樣:n = x + y + z,x∣n,y∣n z∣n和xyz是最大的。

輸入

有多個測試用例。輸入的第一行包含一個整數T(1≤T≤106),顯示測試用例的數量。爲每個測試用例:

第一行包含一個整數n(1≤n≤106)。

輸出

對於每個測試用例,輸出一個表示最大xyz的整數。如果沒有這樣的整數,輸出−1代替。

樣例輸入

3

1

2

3

樣例輸出

-1

-1

1

思路

按照題目意思我們可以設三個數 i,j,h,使這三個數滿足條件,那麼可知道
n=i+j+h
h=n-i-j
n/i爲整數
n/j爲整數
n/h爲整數
這樣我們可以用兩個for循環鑲套

for(i=1;i<n;i++)
{
        .
        .
        .
        for(j=1;j<n-i;j++)
        {
            .
            .
            .
            h=n-i-j;
        }
        .
        .
        .

}

完整代碼如下(這個代碼會超時)

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int main()
{
    int n,s,i,j,k;
    long long int mmax;
    cin >> n;
    while(n--)
    {
        mmax=0;       //用於保留最大值
        cin >> s;
        for(i=1;i<s;i++)   //求i值
        {
            if(s%i==0)     //判斷是否滿足n/i爲整數
            {
                for(j=1;j<s-i;j++)//求j值
                {
                    if(s%j==0)   //判斷是否滿足n/j爲整數
                    {
                        k=s-i-j; // k值爲s-i-j
                        if(s%k==0&&k!=0) //判斷是否滿足n/j爲整數
                        {
                            if(mmax<i*j*k)  //如滿足判斷i*j*k是否爲最大值
                                mmax=i*j*k;
                        }
                    }
                }
            }
        }
        if(mmax==0)     //沒有最大值說明不存在解
        cout << "-1" <<endl;
        else
            cout << mmax << endl;
    }
    return 0;
}

但會發現 這樣提交會超時 但是我們可以通過這個程序來做測試
得到以下數據
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

由以上數據我們可以得到規律

每12個數形成一個循環,在每個循環裏 第1,2,5,7,10,11個數會是-1
每個循環中答案不是-1的數 都是3或者4的倍數
凡是3的倍數的數x 答案爲(x/3)*(x/3)*(x/3)
凡是4的倍數的數x答案爲(x/4)*(x/4)*(x/4)*2
優先判斷是否爲三的倍數

因此我們可以得到優化後的代碼(不能用cin/cout否則也會超時)

正確代碼

#include<stdio.h>
int main()
{
    long long int n, s;
    long long int mmax;
    scanf("%d", &n);
    while (n--)
    {
        mmax = 0;
        scanf("%lld", &s);
        if (s % 12 == 1 || s % 12 == 2 || s % 12 == 5 || s % 12 == 7 || s % 12 == 10 || s % 12 == 11)
            printf("-1\n");
        else
        {
            if (s % 3 == 0)
                mmax = (s / 3)*(s / 3)*(s / 3);
            else
                mmax = (s / 4)*(s / 4)*(s / 4) * 2;
            printf("%lld\n", mmax);
        }
    }
    return 0;
}

wa了多遍 纔得到的 希望各位親能看明白 歡迎留言提問

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章