编程谜语:倒数而不做减法

发布于 2024-07-17 12:10:09 字数 1459 浏览 7 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

浮云落日 2024-07-24 12:10:09
x = param;
while (x > 0) {
    print x;
    x = (x + param) mod (param + 1);
}
x = param;
while (x > 0) {
    print x;
    x = (x + param) mod (param + 1);
}
装纯掩盖桑 2024-07-24 12:10:09

加法和递归怎么样?

public void Print(int i, int max) {
  if ( i < max ) { 
    Print(i+1, max);
  }
  Console.Write(i);
  Console.Write(" ");
}

public void Main(string[] args) {
  int max = Int32.Parse(args[0]);
  Print(1, max);
}

How about adding and recursion?

public void Print(int i, int max) {
  if ( i < max ) { 
    Print(i+1, max);
  }
  Console.Write(i);
  Console.Write(" ");
}

public void Main(string[] args) {
  int max = Int32.Parse(args[0]);
  Print(1, max);
}
残月升风 2024-07-24 12:10:09

这是您错过的一种方法,反复试验:

import java.util.Random;

public class CountDown
{
    public static void main(String[] args)
    {
        Random rand = new Random();

        int currentNum = Integer.parseInt(args[0]);

        while (currentNum != 0)
        {
            System.out.print(currentNum + " ");
            int nextNum = 0;
            while (nextNum + 1 != currentNum) {
               nextNum = rand.nextInt(currentNum);
            }

          currentNum = nextNum;
        }
    }
}

Here's a method you missed, trial and error:

import java.util.Random;

public class CountDown
{
    public static void main(String[] args)
    {
        Random rand = new Random();

        int currentNum = Integer.parseInt(args[0]);

        while (currentNum != 0)
        {
            System.out.print(currentNum + " ");
            int nextNum = 0;
            while (nextNum + 1 != currentNum) {
               nextNum = rand.nextInt(currentNum);
            }

          currentNum = nextNum;
        }
    }
}
森林很绿却致人迷途 2024-07-24 12:10:09

将 1-7 压入堆栈。 一一弹出堆栈。 打印 7-1。 :)

Push 1-7 onto a stack. Pop stack one by one. Print 7-1. :)

云雾 2024-07-24 12:10:09

使用 2 的补码,毕竟这是计算机处理负数的方式。

int Negate(int i)
{
   i = ~i;  // invert bits
   return i + 1; // and add 1
}

void Print(int max)
{
   for( int i = max; i != 0; i += Negate(1) )
   {
     printf("%d ", i);
   }
}

请参阅http://en.wikipedia.org/wiki/2's_complement

use 2's compliment, after all this is how a computer deals with negative numbers.

int Negate(int i)
{
   i = ~i;  // invert bits
   return i + 1; // and add 1
}

void Print(int max)
{
   for( int i = max; i != 0; i += Negate(1) )
   {
     printf("%d ", i);
   }
}

see http://en.wikipedia.org/wiki/2's_complement

独留℉清风醉 2024-07-24 12:10:09

将数字添加到字符串缓冲区中。

String out = "";
for (int i = 0; i < parm; i++)
{
   out = " " + (i+1) + out;
}
System.out.println(out);

Prepend the numbers into a string buffer.

String out = "";
for (int i = 0; i < parm; i++)
{
   out = " " + (i+1) + out;
}
System.out.println(out);
呆° 2024-07-24 12:10:09

c/c++,一点算术溢出:

void Print(int max)
{
   for( int i = max; i > 0; i += 0xFFFFFFFF )
   {
      printf("%d ", i);
   }
}

c/c++, a bit of arithmetic overflow:

void Print(int max)
{
   for( int i = max; i > 0; i += 0xFFFFFFFF )
   {
      printf("%d ", i);
   }
}
听风吹 2024-07-24 12:10:09

我注意到没有人发布最愚蠢的答案,所以我将继续分享它:

int main (int argc, char **argv) {
  if ( ( argc < 1 ) || ( atoi(argv[1]) != 7 ) ) {
    printf("Not supported.\n");
  } else {
    printf("7 6 5 4 3 2 1\n");
  }
}

不要恨我:看到了吗? 我承认这很愚蠢。 :)

I note that nobody posted the stupidest possible answer, so I'll go ahead and share it:

int main (int argc, char **argv) {
  if ( ( argc < 1 ) || ( atoi(argv[1]) != 7 ) ) {
    printf("Not supported.\n");
  } else {
    printf("7 6 5 4 3 2 1\n");
  }
}

Don't hate me: See? I admitted it's stupid. :)

清音悠歌 2024-07-24 12:10:09

使用舍入误差:

void Decrement(int& i)
{
    double d = i * i;
    d = d / (((double)i)+0.000001); // d ends up being just smaller than i
    i = (int)d; // conversion back to an int rounds down.
}

void Print(int max)
{
   for( int i = max; i > 0; Decrement(i) )
   {
     printf("%d ", i);
   }
}

use a rounding error:

void Decrement(int& i)
{
    double d = i * i;
    d = d / (((double)i)+0.000001); // d ends up being just smaller than i
    i = (int)d; // conversion back to an int rounds down.
}

void Print(int max)
{
   for( int i = max; i > 0; Decrement(i) )
   {
     printf("%d ", i);
   }
}
格子衫的從容 2024-07-24 12:10:09

按位算术

常数空间,没有加法、减法、乘法、除法、模数或算术负数:

#include <iostream>
#include <stdlib.h>
int main( int argc, char **argv ) {
    for ( unsigned int value = atoi( argv[ 1 ] ); value; ) {
        std::cout << value << " ";
        for ( unsigned int place = 1; place; place <<= 1 )
            if ( value & place ) {
                value &= ~place;
                break;
            } else
                value |= place;
    }
    std::cout << std::endl;
}   

Bitwise Arithmetic

Constant space, with no additions, subtractions, multiplications, divisions, modulos or arithmetic negations:

#include <iostream>
#include <stdlib.h>
int main( int argc, char **argv ) {
    for ( unsigned int value = atoi( argv[ 1 ] ); value; ) {
        std::cout << value << " ";
        for ( unsigned int place = 1; place; place <<= 1 )
            if ( value & place ) {
                value &= ~place;
                break;
            } else
                value |= place;
    }
    std::cout << std::endl;
}   
薄荷港 2024-07-24 12:10:09

这并不难。 使用模运算符。

for (int n = 7; n <= 49; n += 7) {
  print n mod 8;
}

This is not hard. Use the modulus operator.

for (int n = 7; n <= 49; n += 7) {
  print n mod 8;
}
最美不过初阳 2024-07-24 12:10:09

一个Python版本:

import sys

items = list(xrange(1, int(sys.argv[1])+1))
for i in xrange(len(items)):
    print items.pop()

A python version:

import sys

items = list(xrange(1, int(sys.argv[1])+1))
for i in xrange(len(items)):
    print items.pop()
郁金香雨 2024-07-24 12:10:09

这是作弊吧?

#!/usr/bin/env python 
def countdown(n):
    for i in range(n):
        print n
        n = n + (n + ~n)

只是为了好玩,它的递归兄弟:

def tune_up(n):
    print n
    if n == 0:
        return
    else:
        return tune_up(n + (n + ~n))

This is cheating, right?

#!/usr/bin/env python 
def countdown(n):
    for i in range(n):
        print n
        n = n + (n + ~n)

And just for fun, its recursive brother:

def tune_up(n):
    print n
    if n == 0:
        return
    else:
        return tune_up(n + (n + ~n))
靑春怀旧 2024-07-24 12:10:09

从包含从大到小您感兴趣的递减数字的文件开始:

7 6 5 4 3 2 1

然后...这只适用于 9999

#!/bin/sh
MAX_NUM=9999
if [ ! -e descendingnumbers.txt ]; then
    seq -f%04.0f -s\  $MAX_NUM -1 1 > descendingnumbers.txt
fi
tail descendingnumbers.txt -c $[5 * $1]

Start with a file containing descending numbers from to the max you're interested in:

7 6 5 4 3 2 1

Then... this only works up to 9999

#!/bin/sh
MAX_NUM=9999
if [ ! -e descendingnumbers.txt ]; then
    seq -f%04.0f -s\  $MAX_NUM -1 1 > descendingnumbers.txt
fi
tail descendingnumbers.txt -c $[5 * $1]
小红帽 2024-07-24 12:10:09

Scala 中的快速而肮脏的版本:

sealed abstract class Number
case class Elem(num: Number, value: Int) extends Number
case object Nil extends Number

var num: Number = Nil

for (i <- 1 until param)
  num = Elem(num, i)

while (num != null)
  num match {
    case Elem(n, v) => {
      System.out.print(v + " ")
      num = n
    }
    case Nil => {
      System.out.println("")
      num = null
    }
}

Quick and dirty version in Scala:

sealed abstract class Number
case class Elem(num: Number, value: Int) extends Number
case object Nil extends Number

var num: Number = Nil

for (i <- 1 until param)
  num = Elem(num, i)

while (num != null)
  num match {
    case Elem(n, v) => {
      System.out.print(v + " ")
      num = n
    }
    case Nil => {
      System.out.println("")
      num = null
    }
}
鸵鸟症 2024-07-24 12:10:09

增加传递给 max_int 的有符号整数,然后将其“添加”到计数器中...或者这是否被认为是非法减法?

Increment a signed integer passed max_int and then "Add" it to the counter... or is this consider illegitimate subtraction?

安静 2024-07-24 12:10:09
    public void print (int i)
    {
        Console.Out.Write("{0} ", i);
        int j = i;
        while (j > 1)
        {
            int k = 1;
            while (k+1 < j)
                k++;
            j = k;
            Console.Out.Write("{0} ", k );
        }
    }

有点讨厌,但它确实有效

    public void print (int i)
    {
        Console.Out.Write("{0} ", i);
        int j = i;
        while (j > 1)
        {
            int k = 1;
            while (k+1 < j)
                k++;
            j = k;
            Console.Out.Write("{0} ", k );
        }
    }

Kinda nasty but it does the job

隱形的亼 2024-07-24 12:10:09
public class CountUp
{
    public static void main(String[] args)
    {

        int n = Integer.parseInt(args[0]);

        while (n != 0)
        {
            System.out.print(n + " ");
            n = (int)(n + 0xffffffffL);
        }
    }
}
public class CountUp
{
    public static void main(String[] args)
    {

        int n = Integer.parseInt(args[0]);

        while (n != 0)
        {
            System.out.print(n + " ");
            n = (int)(n + 0xffffffffL);
        }
    }
}
羞稚 2024-07-24 12:10:09
// count up until found the number. the previous number counted is
// the decremented value wanted.
void Decrement(int& i)
{
  int theLastOneWas;
  for( int isThisIt = 0; isThisIt < i; ++isThisIt )
  {
    theLastOneWas = isThisIt;
  }
  i = theLastOneWas;
}

void Print(int max)
{
   for( int i = max; i > 0; Decrement(i) )
   {
     printf("%d ", i);
   }
}
// count up until found the number. the previous number counted is
// the decremented value wanted.
void Decrement(int& i)
{
  int theLastOneWas;
  for( int isThisIt = 0; isThisIt < i; ++isThisIt )
  {
    theLastOneWas = isThisIt;
  }
  i = theLastOneWas;
}

void Print(int max)
{
   for( int i = max; i > 0; Decrement(i) )
   {
     printf("%d ", i);
   }
}
燕归巢 2024-07-24 12:10:09

我们这是在打高尔夫球吗?

import sys
for n in reversed(range(int(sys.argv[1]))):print n+1,

Are we golfing this?

import sys
for n in reversed(range(int(sys.argv[1]))):print n+1,
有木有妳兜一样 2024-07-24 12:10:09
#!/usr/bin/env ruby

ARGV[0].to_i.downto(1) do |n|
  print "#{n} "
end
puts ''
#!/usr/bin/env ruby

ARGV[0].to_i.downto(1) do |n|
  print "#{n} "
end
puts ''
那片花海 2024-07-24 12:10:09

Haskell:

import System.Environment (getArgs)

func :: Integer -> [String]
func 0 = []
func n@(x+1) = show n:func x

main = putStrLn . unwords . func . read . head =<< getArgs

一个称为 n+k 模式的“功能”允许这样:对两个数字相加进行模式匹配。 一般不使用。 一种更惯用的方法是使用此版本的 func:

func n = foldl (flip $ (:) . show) [] [1..n]

或每行一个数字:

import System.Environment (getArgs)
import Data.Traversable

main = foldrM (const . print) () . enumFromTo 1 . read . head =<< getArgs

Haskell:

import System.Environment (getArgs)

func :: Integer -> [String]
func 0 = []
func n@(x+1) = show n:func x

main = putStrLn . unwords . func . read . head =<< getArgs

A 'feature' called n+k patterns allows this: pattern matching on the addition of two numbers. It is generally not used. A more idiomatic way to do it is with this version of func:

func n = foldl (flip $ (:) . show) [] [1..n]

or, with one number per line:

import System.Environment (getArgs)
import Data.Traversable

main = foldrM (const . print) () . enumFromTo 1 . read . head =<< getArgs
浅唱々樱花落 2024-07-24 12:10:09

这算不算? 仅使用添加指令...

int _tmain(int argc, _TCHAR* argv[])
{
   int x = 10;
   __asm mov eax,x;
   __asm mov ebx,0xFFFFFFFF;
   while (x > 0)
   {
      __asm add eax,ebx;
      __asm mov x,eax;
      __asm push eax;
      printf("%d ",x);
      __asm pop eax;
   }
   return 0;
}

Does this count? Only uses an add instruction...

int _tmain(int argc, _TCHAR* argv[])
{
   int x = 10;
   __asm mov eax,x;
   __asm mov ebx,0xFFFFFFFF;
   while (x > 0)
   {
      __asm add eax,ebx;
      __asm mov x,eax;
      __asm push eax;
      printf("%d ",x);
      __asm pop eax;
   }
   return 0;
}
℡Ms空城旧梦 2024-07-24 12:10:09

珀尔:

$n = $ARGV[0];

while ($n > 0) {
  print "$n ";
  $n = int($n * ($n / ($n+1)));
}

Perl:

$n = $ARGV[0];

while ($n > 0) {
  print "$n ";
  $n = int($n * ($n / ($n+1)));
}
酒浓于脸红 2024-07-24 12:10:09

减法无论如何都是一种幻觉

subtraction is an illusion anyways

网白 2024-07-24 12:10:09

我喜欢 Dylan Bennett 的想法——简单、务实,并且它遵循 KISS 原则,恕我直言,这是我们在开发软件时应该始终牢记的最重要的概念之一。 毕竟,我们编写代码主要是为了其他人来维护它,而不是为了让计算机读取它。 Dylan 用古老的 C 语言给出的解决方案:



#include <stdio.h>
int main(void) {
        int n;
        for (n = 7; n <= 49; n += 7) {
                printf("%d ", n % 8);
        }
}

I like Dylan Bennett's idea - simple, pragmatic and it adheres to the K.I.S.S principle, which IMHO is one of the most important concepts we should always try to keep in mind when we develop software. After all we write code primarily for other human beings to maintain it, and not for computers to read it. Dylan's solution in good old C:



#include <stdio.h>
int main(void) {
        int n;
        for (n = 7; n <= 49; n += 7) {
                printf("%d ", n % 8);
        }
}

宁愿没拥抱 2024-07-24 12:10:09

在 C 中,使用旋转内存块(注意,不是我引以为傲的东西......):

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

#define MAX_MAX 10

void rotate_array (int *array, int size) {
  int tmp = array[size - 1];
  memmove(array + 1, array, sizeof(int) * (size - 1));
  array[0] = tmp;
}

int main (int argc, char **argv) {
  int idx, max, tmp_array[MAX_MAX];

  if (argc > 1) {
    max = atoi(argv[1]);
    if (max <= MAX_MAX) {
      /* load the array */
      for (idx = 0; idx < max; ++idx) {
        tmp_array[idx] = idx + 1;
      }
      /* rotate, print, lather, rinse, repeat... */
      for (idx = 0; idx < max; ++idx) {
        rotate_array(tmp_array, max);
        printf("%d ", tmp_array[0]);
      }
      printf("\n");
    }
  }

  return 0;
}

以及将列表视为整数的常见 lisp 解决方案:

(defun foo (max)
  (format t "~{~A~^ ~}~%"
          (maplist (lambda (x) (length x)) (make-list max))))

将其变成可执行文件可能是最难的部分,并作为练习留给读者。

In C, using a rotating memory block (note, not something I'm proud of...):

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

#define MAX_MAX 10

void rotate_array (int *array, int size) {
  int tmp = array[size - 1];
  memmove(array + 1, array, sizeof(int) * (size - 1));
  array[0] = tmp;
}

int main (int argc, char **argv) {
  int idx, max, tmp_array[MAX_MAX];

  if (argc > 1) {
    max = atoi(argv[1]);
    if (max <= MAX_MAX) {
      /* load the array */
      for (idx = 0; idx < max; ++idx) {
        tmp_array[idx] = idx + 1;
      }
      /* rotate, print, lather, rinse, repeat... */
      for (idx = 0; idx < max; ++idx) {
        rotate_array(tmp_array, max);
        printf("%d ", tmp_array[0]);
      }
      printf("\n");
    }
  }

  return 0;
}

And a common lisp solution treating lists as ints:

(defun foo (max)
  (format t "~{~A~^ ~}~%"
          (maplist (lambda (x) (length x)) (make-list max))))

Making this into an executable is probably the hardest part and is left as an exercise to the reader.

逆流 2024-07-24 12:10:09

Common Lisp

从 7 开始倒数(使用递归,或者像这里一样,使用 loopdownto):

(loop for n from 7 downto 1 do (print n) )

或者,也许是一个更有趣的解决方案。 使用复数,我们只需重复添加 i 的平方即可:

(defun complex-decrement (n)
  "Decrements N by adding i squared."
  (+ n (expt (complex 0 1) 2)))

(loop for n = 7 then (complex-decrement n)
      while (> n 0) do (print n))

Common Lisp

Counting down from 7 (with recursion, or like here, using loop and downto):

(loop for n from 7 downto 1 do (print n))

Alternatively, perhaps a more amusing soluting. Using complex numbers, we simply add i squared repeatedly:

(defun complex-decrement (n)
  "Decrements N by adding i squared."
  (+ n (expt (complex 0 1) 2)))

(loop for n = 7 then (complex-decrement n)
      while (> n 0) do (print n))
浮云落日 2024-07-24 12:10:09

我喜欢递归

function printCountDown(int x, int y) {
  if ( y != x ) printCountDown(x, y++);
  print y + " ";
}

你也可以使用乘法

function printNto1(int x) {
  for(int y=x*(MAXINT*2+1);y<=(MAXINT*2+1);y++) {
    print (y*(MAXINT*2+1)) + " ";
  }
}

I like recursive

function printCountDown(int x, int y) {
  if ( y != x ) printCountDown(x, y++);
  print y + " ";
}

You can also use multiplication

function printNto1(int x) {
  for(int y=x*(MAXINT*2+1);y<=(MAXINT*2+1);y++) {
    print (y*(MAXINT*2+1)) + " ";
  }
}
云胡 2024-07-24 12:10:09

另一种 Perl 版本可能是:

#!/usr/local/bin/perl
print reverse join(" ",1 .. $ARGV[0]) . "\n";

An alternative perl version could be:

#!/usr/local/bin/perl
print reverse join(" ",1 .. $ARGV[0]) . "\n";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文