Ruby :: Aufgabe #151

1 Lösung Lösung öffentlich

Symmetrische Primzahlen

Anfänger - Ruby von hollst - 03.04.2017 um 13:55 Uhr
Wieviele Primzahlen P < 1.000.000 sind rückwärts gelesen auch eine Primzahl, jedoch ungleich sich selbst?

Anmerkung: Die (Prim)zahlen 2, 3, 5, 7, 11 erfüllen nicht die Bedingungen (sind rückwärts gelesen sich selbst gleich),
als erste erfüllt die 13 die Bedingungen.

Lösungen:

vote_ok
von Idef1x (1320 Punkte) - 24.01.2018 um 13:44 Uhr
Quellcode ausblenden Ruby-Code
=begin
 T.y.P. #151 Symmetric Primenumbers
 By Lars I.
 lines of code: 29
=end

#=======================================================================================

def symmetricPrimes()
=begin
 IN:
  - Nothing
  
 OUT:
  - symmetricprimes
  
=end

#Section - CODE

 #Section - Findiing the symmetric primes
    
    1.upto(1000000) do |x|
        
        if x % 2 != 0 && x % 3 != 0 && x % 4 != 0 && x % 5 != 0 then
            
            if x.to_s != (x.to_s).reverse then
                
                if isPrime(x) then
                    
                    if isPrime(((x.to_s).reverse).to_i)
                        
                        puts "#{x}"
                        
                    end
                    
                end
                
            end
            
        end
        
    end
    
end

#=======================================================================================

def isPrime(num)
=begin
 IN:
  Num(ber) that has to be tested
 OUT:
  Boolean that expresses whether the number is a prime or not
=end

#Section - CODE

 #Section - isPrime?
    
    if num == 1
        
        return false
        
    elsif num / 2 < 2
        
        lim = num       #for performance
        
    else
        
        lim = num / 2   #for performance
        
    end
    
    for i in 2...lim
        
        if num % i == 0 then
            
            return false
            
        end
        
    end
    
 #Section - Return
 
    return true
    
end

#=======================================================================================

symmetricPrimes()