【算法笔记5.3小节 - 分数的四则运算】问题 A: 分数矩阵

该博客主要探讨了分数矩阵的问题,其中矩阵对角线元素恒为1/1,两侧分数分母依次递增。文章提出了求解矩阵总和的方法,并提供了样例输入和输出。博主分享了AC代码实现,但指出有50%的运行时间超过了限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题 A: 分数矩阵

时间限制: 1 Sec  内存限制: 32 MB
提交: 443  解决: 165
[提交][状态][讨论版][命题人:外部导入]

题目描述

我们定义如下矩阵:
1/1 1/2 1/3
1/2 1/1 1/2
1/3 1/2 1/1
矩阵对角线上的元素始终是1/1,对角线两边分数的分母逐个递增。
请求出这个矩阵的总和。

输入

输入包含多组测试数据。每行给定整数N(N<50000),表示矩阵为N*N。当N=0时,输入结束。

输出

输出答案,结果保留2位小数。

样例输入

1
2
3
4
0

样例输出

1.00
3.00
5.67
8.83
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<iostream>
#include<algorithm>

int main()
{
    int n;
    while(scanf("%d",&n),n!=0)
    {
        double sum=0;
        sum = sum + n*1;
        for(int i=2; i<=n; i++)
        {
            sum = sum + (1.0/double(i))*2*(n-i+1);
        }
        printf("%.2lf\n",sum);
    }

}

 

 

AC代码

n = 3时

i=2  1/2 * (3-2+1) * 2=(1/2)*4

i=3  1/3 * (3-3+1) * 2 = (1/3) * 2

 

我的运行超时50%代码

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<iostream>
#include<algorithm>

struct Fraction{    //分数
    int up, down;   //分子,分母
}a[50010];
int gcd(int a, int b)
{
    if(b==0) return a;
    return gcd(b, a%b);
}
Fraction reduction(Fraction ans)
{
    if(ans.down<0)
    {
        ans.up *=(-1);
        ans.down *=(-1);
    }
    if(ans.up==0)//分母为0
    {
        ans.down = 1;
    }
    else
    {
        int d = gcd(abs(ans.up), abs(ans.down));
        ans.up/=d;
        ans.down/=d;
    }
    return ans;
}
Fraction add(Fraction f1, Fraction f2){
    Fraction ans;
    ans.up = f1.up*f2.down+f2.up+f1.down;
    ans.down = f1.down*f2.down;
    return reduction(ans);  //返回结果分数,注意化简

}

Fraction sub(Fraction f1, Fraction f2){
    Fraction ans;
    ans.up = f1.up*f2.down-f2.up+f1.down;
    ans.down = f1.down*f2.down;
    return reduction(ans);  //返回结果分数,注意化简

}
Fraction multi(Fraction f1, Fraction f2){
    Fraction ans;
    ans.up = f1.up*f2.up;
    ans.down = f1.down*f2.down;
    return reduction(ans);  //返回结果分数,注意化简

}

void show(Fraction r)
{
    r = reduction(r);
    if(r.down==1)
        printf("%lld",r.up);//整数
    else if(abs(r.up)>r.down)
        printf("%d %d/%d",r.up/r.down, abs(r.up)%r.down, r.down);
    else
        printf("%d/%d", r.up, r.down);
}
int main()
{
    int n;
    while(scanf("%d",&n),n!=0)
    {
        double ans=0;
       for(int i=1;i<=n; i++)
        {
            for(int j=1; j<=i; j++)
            {
                ans = ans + 1.0/double(j);
              //  printf("1/%d ", j);
            }
          //  printf("\n");
        }
        ans = (ans-double(n))*2+double(n);
        printf("%.2lf\n",ans);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值