算法 - 初体验

计算 1 + 2 + ... + 99 + 100
算法一:

#include <stdio.h>
#include <string.h>

int main( )
{
    int i,sum = 0,n =100;
    for (i = 1;i<=n;i++) {
        sum = sum + i;
    }
    printf("%d",sum);
    return 0;
}

条件改大一些,

#include <stdio.h>
#include <string.h>

int main( )
{
    int i,sum = 0,n =100000000000;
    for (i = 1;i<=n;i++) {
        sum = sum + i;
    }
    printf("%d",sum);
    return 0;
}
2103145472
Process returned 0 (0x0)   execution time : 4.061 s
Press any key to continue.

执行了4秒钟。

算法二:

#include <stdio.h>
#include <string.h>

int main( )
{
    int i,sum = 0,n =100;
    sum = (1 + n) * (n/2);
    printf("%d",sum);
    return 0;
}

改大一些,

#include <stdio.h>
#include <string.h>

int main( )
{
    int i,sum = 0,n =100000000000;
    sum = (1 + n) * (n /2);
    printf("%d",sum);
    return 0;
}
2103145472
Process returned 0 (0x0)   execution time : 0.206 s
Press any key to continue.

执行0.2秒。

点评: 算法二更加高效。

算法就是你泡妞的技巧和策略,有的朋友技术高,三下五除二就拿下。

对于给定的问题,可以有多种解决的算法。

掌握经典算法,加以灵活运用,产生新的算法。


本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/8278738.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
欢迎来到 tensorflow 初体验第四关! 在这一关中,我们将学习如何使用 TensorFlow 构建一个简单的神经网络,并对手写数字进行分类。 首先,让我们导入所需的库和数据集: ```python import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt # 加载 MNIST 手写数字数据集 mnist = keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() ``` 接下来,让我们对数据进行预处理。我们将把像素值缩放到 0 到 1 的范围内,并将标签转换为 one-hot 编码: ```python # 将像素值缩放到 0 到 1 的范围内 train_images = train_images / 255.0 test_images = test_images / 255.0 # 将标签转换为 one-hot 编码 train_labels = keras.utils.to_categorical(train_labels) test_labels = keras.utils.to_categorical(test_labels) ``` 现在,我们可以构建一个简单的神经网络模型。我们将使用两个隐藏层,每个隐藏层包含 128 个神经元,并使用 softmax 激活函数进行输出: ```python # 构建一个简单的神经网络模型 model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation=tf.nn.relu), keras.layers.Dense(128, activation=tf.nn.relu), keras.layers.Dense(10, activation=tf.nn.softmax) ]) ``` 接下来,我们需要编译模型并指定损失函数、优化器和评估指标: ```python # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ``` 最后,我们可以训练模型并评估其性能: ```python # 训练模型 model.fit(train_images, train_labels, epochs=5) # 评估模型 test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) ``` 恭喜你完成了 tensorflow 初体验第四关!现在你已经知道如何构建一个简单的神经网络,并对手写数字进行分类。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值