Page 1 of 8 123 ... LastLast
Results 1 to 10 of 77

Thread: "Check the Number is Prime" in every Programming Language

  1. #1
    Join Date
    Dec 2006
    Location
    Hogwarts, `UNKNOWN`
    Beans
    Hidden!
    Distro
    Ubuntu 8.10 Intrepid Ibex

    "Check the Number is Prime" in every Programming Language

    First of all my apologies for literally stealing the idea from this thread which I found very interesting. However a "Hello Ubuntu" program will lack the concept of conditions and iterations, so I wondered it would be great to have a thread which would showcase these concepts in every programming language. So This is the thread for program which will:
    (1) Get a number as User Input.
    (2) Determine whether the number is Prime or Not and hence display the output.
    I guess it would be interesting to see , particularly how iterations are implmented in programming languages which do not have loops.
    Also Rules:
    (1) Do Not Use a Built in Function for determining a prime.
    (2) The code should be clean.
    (3) Use this site so that you can use the [CODE] tags to have syntax highlighting. Unfortunately I don't think [PHP] tag would really suffice IMO except for PHP of course.
    (4) You can post in languages already posted, but a different algorithm would be appreciated.
    (5) Please specify the programming language.

    Thanks.
    Last edited by Canis familiaris; October 7th, 2008 at 11:39 AM.

  2. #2
    Join Date
    Dec 2006
    Location
    Hogwarts, `UNKNOWN`
    Beans
    Hidden!
    Distro
    Ubuntu 8.10 Intrepid Ibex

    Re: "Check the Number is Prime" in every Programming Language

    My Entries:
    Python

    Code:
    #!/usr/bin/python
    num = input('Enter the number which you wish to determine it is prime: ')
    
    if num < 2:
    	print "\nThe Number", num, " is not a prime!"
    else:
    	for div in range(2, (num/2)+1):
    		if num%div==0:
    			print "\nThe Number", num, " is not a prime!"
    			break
    	else:
    		print "\nThe Number", num, " is a prime!"
    C
    Code:
    #include<stdio.h>
    
    int main()
    {
    	int div;
    	int num;
    	
    	printf("Enter a number: ");
    	scanf("%d", &num);
    	
    	if(num>=2)
    		for(div=2; div <= num/2; div++)
    			if((num%div)==0)
    				break;
    				
    	if(num>1 && (!(div<=num/2)))
    		printf("\nThe number %d is a prime.", num);
    	else	
    		printf("\nThe number %d is not a prime", num);
    		
    	return 0;			
    }
    C++
    Code:
    #include<iostream>
    using namespace std;
    
    int main()
    {
    	int div;
    	int num;
    	
    	cout<<"Enter a number: ";
    	cin>>num;
    	
    	if(num>=2)
    		for(div=2; div <= num/2; div++)
    			if((num%div)==0)
    				break;
    				
    	if(num>1 && (!(div<=num/2)))
    		cout<<"The number "<<num<<" is a prime\n";
    	else	
    		cout<<"The number "<<num<<" is not a prime\n";
    	
    		
    	return 0;			
    }
    Special Thanks to Reiger for correcting the Code in C and C++


    I am a newbie in programming, particularly Python, so please highlight my mistakes and give tips.
    Last edited by Canis familiaris; October 7th, 2008 at 05:24 PM. Reason: Corrected the incorrect code. The last number had to be inclusive

  3. #3
    Join Date
    Sep 2005
    Location
    Reading, Berkshire, UK
    Beans
    25

    Re: "Check the Number is Prime" in every Programming Language

    Just a note - you only need to go up to the square root of the number, not above (well, for the sake of your code, one above the square root will make better sense).

    Ideally, you would only need to do the division for prime numbers below the square root of the number, but I can't work out a way of doing that that's actually less expensive than doing it your way.

  4. #4
    Join Date
    Dec 2006
    Location
    Hogwarts, `UNKNOWN`
    Beans
    Hidden!
    Distro
    Ubuntu 8.10 Intrepid Ibex

    Re: "Check the Number is Prime" in every Programming Language

    Quote Originally Posted by Borusa View Post
    Just a note - you only need to go up to the square root of the number, not above (well, for the sake of your code, one above the square root will make better sense).

    Ideally, you would only need to do the division for prime numbers below the square root of the number, but I can't work out a way of doing that that's actually less expensive than doing it your way.
    Thanks but I don't think it will make much difference since the loop will terminate when it finds the lowest factor.
    Good Idea, neverthless.

    Though I think the best implementation would be the loop to list prime number and check the divisibility. This would result in a much more efficient cycle. But I am not sure how to implement it.

    Python
    Code:
    #!/usr/bin/python
    num = input('Enter the number which you wish to determine it is prime: ')
    
    for div in range(2, (num/2)+1):
    	if num%div==0:
    		print "\nThe Number", num, " is not a prime!"
    		break
    else:
    	print "\nThe Number", num, " is a prime!"
    Also I was wondering is there a way to have the last number in the range() to be inclusive rather than exclusive in Python. I am not really liking the statement (num/2)+1.
    Last edited by Canis familiaris; October 7th, 2008 at 12:56 PM.

  5. #5
    Join Date
    Jul 2008
    Beans
    1,491

    Re: "Check the Number is Prime" in every Programming Language

    A quick Haskell version:
    Code:
    module Test where
    import Char
    
    getInput i = (putStrLn i) >> getLine
    
    run i = do
            s <- getInput i
            if (all isDigit s)
              then (return (read s :: Integer))
              else (run "That's not a Positive Integer, and therefore it cannot possibly be prime! Please try again:")
    
    primes (x:xs) = x : ( primes $ filter (`isRelativePrimeTo` x) xs )
    primes  x         = x
    
    isRelativePrimeTo = \x y -> x `mod` y /= 0
    
    
    isPrime q = and $ map (q `isRelativePrimeTo`) $ primes $ [2..(floor $ sqrt $ fromInteger q)]
    
    main =  do
            q <- (run "Please enter the number which might be prime:")
            if ((q>1) && (isPrime q))
              then (putStrLn $ "Indeed, "++(show q)++" is prime!")
              else (putStrLn $ "No, "++(show q)++" is not prime!")
    Optimised a little.
    Last edited by Reiger; October 7th, 2008 at 03:48 PM.

  6. #6
    Join Date
    Sep 2008
    Location
    Korea
    Beans
    938
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: "Check the Number is Prime" in every Programming Language

    In the C and C++ versions you are only checking whether the number is even. You want to replace num%2 by num%dev.

  7. #7
    Join Date
    Dec 2006
    Location
    Hogwarts, `UNKNOWN`
    Beans
    Hidden!
    Distro
    Ubuntu 8.10 Intrepid Ibex

    Re: "Check the Number is Prime" in every Programming Language

    Quote Originally Posted by Idefix82 View Post
    In the C and C++ versions you are only checking whether the number is even. You want to replace num%2 by num%dev.
    Oops! My mistake. I think I posted the wrong Code.
    I guess this is some indication I'm out of practice.
    Last edited by Canis familiaris; October 7th, 2008 at 01:18 PM.

  8. #8
    Join Date
    Feb 2007
    Beans
    4,045
    Distro
    Ubuntu 9.10 Karmic Koala

    Re: "Check the Number is Prime" in every Programming Language

    Code:
    #!/bin/bash
    
    # Simple way of approximating the square root using integer arithmetics
    sqrt() # $1 - number
    {
        local i=1 j=1 n=$1
        while (( i*i <= n )); do
            ((j=i, i++))
        done
        echo "$j"
    }
    
    isprime() # $1 - number
    {
        local i=3 n=$1 h=0
    
        # Only considering 2 or greater
        (( n >= 2 )) || return
    
        # Trivial cases
        (( n == 2 || n == 3 )) && return
    
        (( n % 2 == 0 )) && return 1
        h=$(( $(sqrt "$n") + 1 ))
        while (( i < h )); do
            (( n % i == 0 )) && return 1
            (( i += 2 ))
        done
        return 0
    }
    
    
    # If no arguments are given, prompt for an integer
    if (( $# == 0 )); then 
        read -p "Enter integer number: " n || exit
    else
        n=$1
    fi
    
    if isprime "$n"; then
        echo "$n is prime"
    else
        echo "$n is not prime"
    fi
    Last edited by geirha; March 12th, 2011 at 06:12 PM. Reason: Altered to follow good practices

  9. #9
    Join Date
    Jan 2006
    Beans
    Hidden!
    Distro
    Ubuntu 10.10 Maverick Meerkat

    Re: "Check the Number is Prime" in every Programming Language

    Perl.

    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    sub isprime {
      my $num = shift;
      if ($num < 2) return false;
      if ($num == 2) return true;
      else for (my $i = 2; $i < sqrt($num); $i++) { if ($num % $i == 0) return false; }
      return true;
    }
    
    while (<>) {
      if (isprime($_)) {
        print $_ . " is prime\n";
      }
      else print $_ . " is not prime\n";
    }
    Last edited by slavik; October 7th, 2008 at 03:48 PM.
    I am infallible, you should know that by now.
    "My favorite language is call STAR. It's extremely concise. It has exactly one verb '*', which does exactly what I want at the moment." --Larry Wall
    (02:15:31 PM) ***TimToady and snake oil go way back...
    42 lines of Perl - SHI - Home Site

  10. #10

    Re: "Check the Number is Prime" in every Programming Language

    Lua

    Code:
    local number = io.read("*n")
    local isPrime = true
    
    for i = 2, math.sqrt(number) do
    	if number % i == 0 then
    		isPrime = false
    		break
    	end
    end
    
    if isPrime then print("Is prime!") else print("Isn't prime!") end

Page 1 of 8 123 ... LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •