首页 > 试题广场 >

【编程题】求解f(n), f(n) = 1 – 2 + 3

[问答题]
【编程题】求解f(n), f(n) = 1 – 2 + 3 – 4 + 5 - … + n 

如果是偶数就是0减去n/2

基数就是n减去n/2

发表于 2020-03-18 11:39:59 回复(0)
import java.util.Scanner;
public class dijia {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        in.close();
        if(n%2==1){
            System.out.println((n+1)/2);
        }
        else{
            System.out.println(-(n/2));
        }
    }
}

发表于 2019-08-19 15:48:22 回复(0)
import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);        
        int n = reader.nextInt();
        
        if(n%2==0){
            double resulteven = (1.0+n-1)*n/4;
            double resultodd = (2.0+n)*n/4;
            System.out.println(resulteven-resultodd);
        }    
        else{
            double resulteven = (1.0+n)*n/4;
            double resultodd = (1.0+n-1)*(n/2-1)/2;
            System.out.println(resulteven-resultodd);
        }
    }
}
这种题不可能单纯的考你硬编码,穷举都能写出来,如果提交的话,肯定不能百分百case,超时,编写之前一定要优化算法。切记切记。
发表于 2018-09-21 21:18:30 回复(0)
#include <iostream>
using namespace std;
int main()
{
    int n,Sum=0;
    cin>>n;

    for   (int i=1;i<n+1;i++)
    {
        Sum+=pow(-1,i+1)*i;
    }
    return 0;
}

发表于 2021-02-24 15:16:14 回复(1)
def func(n):
    if n%2==1:
        return (n+1)/2
    return -n/2
x = input()
print(func(x))
Python方法
发表于 2019-08-31 21:25:22 回复(0)
import java.util.Scanner; public class Main22{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int res=fun(n); System.out.println("结果是:"+res);
    } public static int fun(int n){ if(n==0) return 0; int res=0; for(int i=1;i<=n;i++){ if(i%2==1){
                res=res+i;
            } else{
                res=res-i;
            }
        } return res;
    }
}


发表于 2019-04-19 22:32:00 回复(0)
public class Solution{
     public static void main(String[] args){
         int n;
         int sum = 0;
         for(int i = 1 ; i<=n ; i++){
              if(i%2 == 0){
                 sum -= i;
                 }else{  sum += i; 
                    }
              }
         }
}

发表于 2018-08-30 16:51:59 回复(0)
function f(n){
    if(n<0){
        return false;
    }
    let sum = 0;
    while(n>=1){
        let count = 1;
        if(n%2 === 0){
            count = -1;
    }
        sum += count*n;
        n--;
    }
    return sum;
}

发表于 2018-07-22 17:30:42 回复(0)