python - Python 中的素数和完美平方检查器

标签 python algorithm primes perfect-square

我正在尝试使用 Python 编写我自己的素数和完美平方检查器, 如果这是一个素数,该函数应该打印“Foo”,如果这是一个完美的正方形,则打印“Bar”,如果两者都不是,则打印“FooBar” 这是我的代码:

def FooBar():
    prime = True
    perfSqr = False
    for target in range(100,100001):
        for num in range(1,target+1):
            if target % num == 0 and num != target:
                prime = False

            if target // num == num and target % num == 0:
                perfSqr = True

    if prime is True:
        print 'Foo'
    elif perfSqr is True:
        print 'Bar'
    else:
        print 'FooBar'

if __name__ == '__main__':
    FooBar()

不知何故,我根本无法运行它,任何人都可以给我一些提示吗?

最佳答案

几件事。第一个是您从 1 运行 numtarget + 1num % 1 始终为 0,因此您永远不会打印任何素数。

接下来,您不会在迭代中重置您的 primeperfSqr 标志。此外,您需要将打印语句移到外循环中,以便它们打印每次迭代。

这按预期工作:

def FooBar():
    for target in range(100, 100001):
        prime = True
        perfSqr = False
        for num in range(2, target + 1):
            if target % num == 0 and num != target :
                prime = False

            if target // num == num and target % num == 0:
                perfSqr = True

        if prime or perfSqr:
            print(num, end=', ')
            if prime:
                print('Foo', end=', ')
            elif perfSqr:
                print('Bar', end=' ')
            print('\n')

关于python - Python 中的素数和完美平方检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45021432/

相关文章:

python - 多维 numpy 数组中的数组索引

php - 在PHP中获取嵌套数组的算法

java - 素数代码

c++ - 对为什么我的算法运行速度比应有的速度慢感到困惑

python - 如何将python脚本添加到Windows系统路径?

python - 当 Pandas 中当前名称为 NaT 时如何更改列名称

python - 问题获取最大子数组的开始

java - 使用 BigInteger 查找 200 位素数

python - 如何删除 Pandas 数据框中的唯一行

algorithm - 哈希表 vs 平衡二叉树