c++变化的x,编译问题

对2 以上(包括 2)n 以下(包括 n)的正整数x 可以进行以下操作。

如果x+1<=n,x+1可变为新的x

如果sqrt(x)为整数,sqrt(x)可变为新的x

小明想知道从x=2开始,将所有允许的操作都执行至少一遍,使x 的值再次为2的方法中,操作

次数最少的方法的操作次数.

你的任务就是判断这样的方法是否存在,如果存在,则输出最小操作次数。

输入 1行, 1个整数 n。

输出 1行最小操作次数。当不存在符合条件的方法时输出-1。

输入

9
输出

10
输入

5
输出

-1
输入
1000000
输出

333333999
这是我的代码:

#include <iostream>
#include <cstdio>
#include<algorithm>
using namespace std;
int a[100];
int b[100];
int main(){
//    freopen("bhdx.in","r",stdin);
//    freopen(“bhdx.out","w",stdout);
    int n;
    cin>>n;
int x=2,sum=0;


    for(int i=0;i<=10000;i++){
if(x+1<=n){
    x=x+1;
    sum++;
}
else return 0;
if(x==2){
    break;
}
if(sqrt(x)%2==0){
    x=sqrt(x);
    sum++;
}
    }
cout<<sum;

    
    fclose(stdin);
    fclose(stdout);
    
    return 0;
}

这个从书上看到的不知道怎么解决,谁能帮一下,编译错误了,不太明白题意

改动:1用sqrt需要cmath函数;

2.你24行总报错,我帮你改了一下,应该同等,意思是平方根的值(系统保留整数)是否与平方根的值的floor相等

ps:注意程序还是通不过样例


#include<iostream>
#include <cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int a[100];
int b[100];
int main(){
//    freopen("xlh.in","r",stdin);
//    freopen("xlh.out","w",stdout);
    int n;
    cin>>n;
int x=2,sum=0;
 
 
    for(int i=0;i<=10000;i++){
if(x+1<=n){
    x=x+1;
    sum++;
}
else return 0;
if(x==2){
    break;
}
if(sqrt(x)==floor(sqrt(x))){
    x=sqrt(x);
    sum++;
}
    }
cout<<sum;
 
    
    fclose(stdin);
    fclose(stdout);
    
    return 0;
}
 
采纳一下,开心一夏!

没有人吗,感觉对于大家来说小菜一碟