Page 1 of 2

challenge to convert C code to python (prime numbers)

Unread postPosted: 27 Nov 2018, 20:54
by compsystems
Hello, a small challenge to convert the following code to python numworks, ti83, hpprime, ...


Code: Select all
#include <stdio.h>
int isPrime(int n);

int main()
{
int n, cont, i;   
printf("How many consecutive primes you want to see? ");   
scanf("%d",&n);   
cont=1;   
i=2;
while( cont<=n )   
{
    if( isPrime(i) )       
    { 
        printf("%d\n",i);         
        cont = cont+1;     
    }
    i = i+1;   
}
return 0;
}

int isPrime(int n)
{
    int test_prime=1;
    for( int i=2; i<n && test_prime==1; i++ ){
        if( n%i==0 )       
        {
            test_prime = 0;     
        }
    }
    return test_prime;
}

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 27 Nov 2018, 22:05
by gam
you want it specially in Python for calculator or in normal Python?

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 27 Nov 2018, 22:37
by jean-baptiste boric
I don't see what's the "challenge" here. It took me about one minute to make a straightforward conversion to Python:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
def isPrime(n):
    test_prime=1;
    i=2
    while i<n and test_prime==1:
        if n%i==0:
            test_prime = 0
        i+=1
    return test_prime

n = int(input("How many consecutive primes you want to see? "))
cont=1
i=2
while cont<=n:
    if isPrime(i):
        print(i)         
        cont = cont+1
    i = i+1

By the way, that's not what I would call good C code. While keeping the same algorithm, a much cleaner Python version would be:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
def isPrime(n):
  for i in range(2, n):
    if n % i == 0:
      return False
  return True

n = 2
counter = int(input("How many consecutive primes you want to see? "))
while counter > 0:
  if isPrime(n):
    print(n)
    counter -= 1
  n += 1

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 27 Nov 2018, 22:45
by Extra44
My version, a "copy code" from C to python
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
def isPrime(n):
    test_prime=1
    for i in range(2,n):
        if n % i == 0:
            test_prime=0
            break
    return test_prime

n=int(input("How many consecutive primes you want to see? "))
cont = 1
i=2
while cont<=n:
    if isPrime(i):
        print(i)
        cont=cont+1
    i=i+1

:)

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 28 Nov 2018, 07:08
by parisse
You don't have to loop until n. In C you should do
Code: Select all
for (int i=2;i*i<=n;++i){
  if (n%i==0) return false;
}

Since Python does not have a (IMHO) decent for loop, you must use a while loop in Python to do the same.

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 28 Nov 2018, 18:35
by jean-baptiste boric
Well, there's a easy way to achieve this:
Show/Hide spoilerAfficher/Masquer le spoiler
Code: Select all
from math import sqrt

def isPrime(n):
  for i in range(2, int(sqrt(n)+1)):
    if n % i == 0:
      return False
  return True

But yes, Python does not offer C-like for loops, but for-each loops instead. Given the emphasis on lambdas and functional programming in Python, it does not really surprise me. I bet hardcore Python programmers can write a one-liner for returning the first n primes using just map(), filter(), reduce(), range() and lambdas...

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 28 Nov 2018, 18:43
by Adriweb
Apparently... sum([ True if a%factor == 0 else False for factor in ( [2] + list(range(3,int(math.sqrt(a)),2) )) ])

From https://gist.github.com/cescapa/c655e8e0c1558660150f

https://stackoverflow.com/questions/106 ... n-one-line is also interesting I suppose

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 28 Nov 2018, 20:30
by parisse
@jb boric: But you must compute sqrt(n) with approx computations and use a range. While my C loop does not use approx operations, only basic objects (integers), and basic arithmetic on integers. No lists or complex substitutes to avoid memory usage. And the code is easy to understand and efficient (of course it's not efficient for large integers but more efficient algorithms require more math input).

@adriweb: that style of coding is an horror, unreadable, and it's inefficient (well, I'm not certain you can determine how the Python interpreter does certain things). In other words it's garbage for me.

That's some reasons why I don't like Python, it will encourage using complex data types instead of simple ones and/or implement inefficient algorithms... Of course teaching C at highschool level is not a good idea, but my code would work the same in Javascript (just remove the int data type).

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 29 Nov 2018, 01:52
by Adriweb
parisse wrote:@adriweb: that style of coding is an horror, unreadable, and it's inefficient (well, I'm not certain you can determine how the Python interpreter does certain things). In other words it's garbage for me.

That's some reasons why I don't like Python

Yes, I have the same opinion actually (except maybe for the efficiency part, where python implementations probably perform just as fast as the normal way of writing that algorithm, I guess...)

Re: challenge to convert C code to python (prime numbers)

Unread postPosted: 29 Nov 2018, 04:41
by blouson
c'est pas pour faire mon fayot , mais ce genre de code est beaucoup moins clair et compréhensible qu'algobox , franchement je plains les élèves de seconde qui vont devoir se coltiner ce genre de code , ou alors faut déjà être ingénieur en informatique , je sais pas ..